Software construction tips: summary of some methods of thread

thread method summary

For the minor problems encountered during review, the courseware given by the teacher did not explain in detail: several methods were used in judging the thread status: such as Thread.interrupt(), Thread.interrupted(),Thread.isInterrupted(), etc. What's the difference between them? I flipped through the java source code a little, and briefly summarized it here:

1.Thread.interrupt()

public void interrupt() {
        if (this != Thread.currentThread())
            checkAccess();

        synchronized (blockerLock) {
            Interruptible b = blocker;
            if (b != null) {
                interrupt0();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        interrupt0();
    }

The function of this method is to interrupt the execution of the current thread. If the interrupt is the thread itself, it can be executed directly. If it is another thread, the checkAccess method will be called to check permissions. If the current thread is blocked due to calling Object.wait(), or the join() method of the thread itself, calling the interrupt method at this time will throw an InterruptedException, and the blocking state of the thread will be cleared.

2.Thread.interrupted()

public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

This method is very concise because it only calls the isInterrupted method of the currentThread class. interrupted is a static method, and a boolean: true is passed to isInterrupted, which means that the thread's state will be reset to uninterrupted after a call to interrupted.

3.isinterrupted()

public boolean isInterrupted() {
        return isInterrupted(false);
    }

The parameterized method of isInterrupted(boolean ClearInterrupted) is called:

/**
     * Tests if some Thread has been interrupted.  The interrupted state
     * is reset or not based on the value of ClearInterrupted that is
     * passed.
     */
    private native boolean isInterrupted(boolean ClearInterrupted);

If this parameter is true, the interrupt state is reset, otherwise it will not be reset. Since isinterrupted is passed in is false, the interrupted state of the thread will not be changed.
It can be seen that the biggest difference between interrupted and isInterrupted is whether to reset the state.

4.sleep()

public static void sleep(long millis, int nanos)
    throws InterruptedException {
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        sleep(millis);
    }

Make the thread sleep, you can see that there is a limit to the sleep time. The first parameter is milliseconds and the second parameter is nanoseconds.

5.yield()

 /**
     * A hint to the scheduler that the current thread is willing to yield
     * its current use of a processor. The scheduler is free to ignore this
     * hint.
     *
     * <p> Yield is a heuristic attempt to improve relative progression
     * between threads that would otherwise over-utilise a CPU. Its use
     * should be combined with detailed profiling and benchmarking to
     * ensure that it actually has the desired effect.
     *
     * <p> It is rarely appropriate to use this method. It may be useful
     * for debugging or testing purposes, where it may help to reproduce
     * bugs due to race conditions. It may also be useful when designing
     * concurrency control constructs such as the ones in the
     * {@link java.util.concurrent.locks} package.
     */
    public static native void yield();

A hint to the scheduler that the current thread is willing to give up the processor it is currently using, the scheduler is free to ignore this hint.

6.join()

public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

Reading the source code shows that thread A calls the join() method of thread B, which will make A wait for B to execute until thread B terminates. If the parameter is passed in, A will wait for B to execute the time. If the time arrives, it will switch to the A thread and continue to execute the A thread. If the parameter is less than 0, an IllegalArgumentException will be thrown.

Posted by izy on Tue, 31 May 2022 09:54:57 +0530