Why should you use a logical AND interrupt () to signal the end of a stream?

I read about how to end a thread at https://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html , which is the link I found from the question How do you kill a thread in Java ?

The first link first discusses the use of a variable volatileto feed the signal to the stream you want to terminate. The thread must check this variable and terminate the operation if the variable has a value that means termination (for example, if it is null). So, in order to interrupt the stream, you must set this variable to null.

They then discuss the addition of interrupts to help with threads that block for extended periods of time. They give the following example of the stop () method, which sets the volatile (waiter) variable to null, and then ALSO throws an interrupt.

public void stop() {
    Thread moribund = waiter;
    waiter = null;
    moribund.interrupt();
}

I'm just wondering why both of you? Why not ONLY use interrupt () and then handle it correctly? It seems redundant to me.

+4
source share
3 answers

Refer to this documentation . Your thread should check the status thread.isInterrupted(), for example:

Thread myThread = new Thread()  {
    @Override
    public void run() {
        while (!this.isInterrupted()) {
            System.out.println("I'm working");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //We would like also exit from the thread
                return;
            }
        }
    }
};

And if you want to stop the flow, you must call

myThread.interrupt();

, Thread.interrupted(), , , myThread.interrupt(), . Thread.interrupted().

.

volatile.

volatile, @lexicore, , .

+1

( , , . , , .)

. api.

, , . apis, , .

-, , , . , , , , . - .

, , , InterruptedException isInterrupted InterruptedIoException . finally, IOException, , InterruptedException IOException, . , , , ,

? .

  • , .

  • Java 5 concurrency , . , , , , . , . , , , . , java 5 .

, youre , , - , .

( rant, )

, . :

1) , , . . InterruptedException , while, , . .

2), , , . - , . .

3) . Oracle , API. . , , , , , , . , .

, ; suspend/resume.

+3

@NathanHughes , : .

" ", - - . concurrency. reset . , .

, .

, , , ThreadPoolExecutor. ... reset . ? Runnable , Runnable . , , ... , ? Runnable ( ) Runnable, - . isCancelled FutureTask. reset Runnable. ?

Thread#interruptcompletely separated from the real work units working on this thread, so you need to add an additional flag. And as soon as you begin to do this, you must do this to the very extreme and to the most internal working unit. In fact, running unknown user code in your threads makes it Thread#interruptedunreliable (even if Thread#interruptit still works fine!)

0
source

Source: https://habr.com/ru/post/1695479/


All Articles