Single Thread.interrupt () interrupts more than once

I created MyTaskin which there are 3 things inside run(). I am trying a interrupt()thread that contains an instance MyTask. Unfortunately, as soon as it is interrupted, it ends, and only a line is printed on the console First task.

public class MyTask implements Runnable {
    private volatile Thread thread;

    @Override
    public void run() {
        while (!thread.isInterrupted()) {
            System.out.println("First task");
        }
        while (!thread.isInterrupted()) {
            System.out.println("Second task");
        }
        while (!thread.isInterrupted()) {
            System.out.println("Third task");
        }
    }

    public Thread start(){
        thread = new Thread(this);
        thread.start();
        return thread;
    }


    public static void main(String[] args) throws InterruptedException {
        Thread t = new MyTask().start();
        Thread.sleep(1000);
        t.interrupt();
        Thread.sleep(1000);
        t.interrupt();
        Thread.sleep(1000);
        t.interrupt();
    }

}

If I add Thread.sleep(10)in run(), it will start working correctly , and it prints First task, Second taskand finally Third taskon the console.

Question: Whydoes only Thread.interrupts()works correctly if I add sleep()?

public class MyTask implements Runnable {
    private volatile Thread thread;

    @Override
    public void run() {
        while (!thread.isInterrupted()) {
            System.out.println("First task");
        }
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
        while (!thread.isInterrupted()) {
            System.out.println("Second task");
        }
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
        while (!thread.isInterrupted()) {
            System.out.println("Third task");
        }
    }

    public Thread start(){
        thread = new Thread(this);
        thread.start();
        return thread;
    }


    public static void main(String[] args) throws InterruptedException {
        Thread t = new MyTask().start();
        Thread.sleep(1000);
        t.interrupt();
        Thread.sleep(1000);
        t.interrupt();
        Thread.sleep(1000);
        t.interrupt();
    }

}
+4
source share
2 answers

For a quote from Interrupt :

, Thread.interrupted, . isInterrupted, , .

: thread.isInterrupted() Thread.interrupted() .

sleep() , InterruptedException ( )

+4

Javadoc Thread.sleep(long)

Throws: InterruptedException - - . .

, , sleep, ( ) .

:

sleep():

  • interrupted = false, , 1-
  • , .. interrupted = true
  • 1- interrupted ()
  • interrupted
  • interrupted

sleep()

  • interrupted = false
  • loop 1:

    • , interrupted = false
    • , .. interrupted = true
    • , interrupted = true,
    • sleep() , , interrupted = false
    • ( ),
  • 2 2 3

0

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


All Articles