Java – the program continues to run despite the interruptedexception

I started learning Java, and now I'm in the concurrency chapter After reading something about concurrency, I tried my own example

public class Task implements Runnable{

public void run() {
    while(!Thread.interrupted()) {
        try {
            System.out.println("task");
            TimeUnit.SECONDS.sleep(2);
        }catch (InterruptedException e) {
            System.out.println("interrupted");
        }
    }
}

}

public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newCachedThreadPool();
    exec.execute(new Task());
    TimeUnit.SECONDS.sleep(10);
    exec.shutdownNow();
}

The problem is that I look forward to seeing the following output:

task
task
task
task
task
interrupted

But after I get this, the program will continue to print until I close it So my question is what did I do wrong? Why does the program continue printing?

Solution

The section on Java tutorials about concurrency interrupt explains this problem well:

Therefore, when you catch the interruptedexception in the loop, the interrupt state has been reset, so the next time you call thread Interrupted () returns false, which in turn keeps the while loop running To stop the loop, you have the following options:

>Exit the loop with break > exit the entire method with return > move the try catch block outside the while loop (recommended by Nathan Hughes) > call interrupt() on the current thread to set the interrupt flag again > use a separate Boolean value to control the loop and set the flag accordingly in the catch block > use scheduledexecutorservice and delete the loop from the run method of runnable, Make tasks repetitive

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>