简体   繁体   中英

Can't stop thread in Java

I'm trying to create a thread and then interrupt it. But it doesn't stop and cause exception. Can anybody explain what am I doing wrong? Thanks.

public class Test {
    public static void main(String[] args) throws InterruptedException {
        //Add your code here - добавь код тут
        TestThread test = new TestThread();
        test.start();
        Thread.sleep(5000);
        test.interrupt();

    }

    public static class TestThread extends Thread {
        public void run() {
            while (!this.isInterrupted()) {
                try {
                    Thread.sleep(1000);
                    System.out.println("I did the Thread");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

According to javadocs :

A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.

Since you sleep the thread for 1000ms, when you call test.interrupt() , thread is asleep, almost all the times. So InterruptedException will be thrown. Therefore you should exit the loop at the catch clause.

Include a break when you catch InterruptedException to exit while loop.

 while (!this.isInterrupted()) {
            try {
                Thread.sleep(1000);
                System.out.println("I did the Thread");
            } catch (InterruptedException e) {
                break;
            }
        }

The internal flag gets resetted after calling interrupt . You have to call it again in your catch of the thread . The topic was also covered in the Java Specialists Newsletter

In my example, after I caught the InterruptedException, I used Thread.currentThread().interrupt() to immediately interrupted the thread again. Why is this necessary? When the exception is thrown, the interrupted flag is cleared, so if you have nested loops, you will cause trouble in the outer loops

Something like this should work:

   try {
            Thread.sleep(1000);
            System.out.println("I did the Thread");
        } catch (InterruptedException e) {
            this.interrupt();
           // No need for break
        }

This makes sure that the rest of the code is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM