线程中断不起作用

时间:2014-05-20 17:48:16

标签: java multithreading

我只是在研究线程和中断。我得到了一个小例子。不幸的是我没有 看到不稳定的工作。有人能告诉我代码有什么问题: -

public class SleeperTest{
    public static void main(String[] args) throws InterruptedException{
        Runnable sleeper = new Runnable(){
            public void run(){
                // try{
                // System.out.println("Sleeper is going to sleep");
                // Thread.sleep(2000);
                // System.out.println("Sleeper is awake");
                // }
                // catch(InterruptedException e){
                // System.out.println("Sleeper got interrupted");
                // }
                // System.out.println("Hello Ben");
                if(Thread.interrupted()){
                System.out.println("Thread has been interrupted");
                System.out.println(Thread.currentThread().isInterrupted());
                }

            }
        };

        Thread t = new Thread(sleeper);
        t.start();
        Thread.sleep(500);
        t.interrupt();
    }
}

它不会进入被打断的区块。有人可以告诉我为什么吗?

谢谢, 本

2 个答案:

答案 0 :(得分:2)

我尝试在(number)中为两个线程注释可能的执行流程。

主线程

        Thread t = new Thread(sleeper);
        t.start();                           <<< (1) your thread is started; its execution now runs in parallel to this thread
        Thread.sleep(500);                   <<< (2) this thread is now sleeping; the "sleeper" thread is still running!
        t.interrupt();                       <<< (3) 500 milliseconds (0.5 second) later, trying to interrupt, but that thread is most likely already finished by now; this is a no-op

卧铺线程:

        public void run() {                   <<< (1) this thread starting 
            if (Thread.interrupted()) {       <<< (2.1) Am I interrupted? (Not yet, so no)
                 System.out.println("Thread has been interrupted");
                 System.out.println(Thread.currentThread().isInterrupted());
                                              <<< (2.2) Finished executing. This thread is done.
            }
        }

答案 1 :(得分:1)

你有竞争条件。创建的线程在主线程可以中断之前执行并传递if块。

中断通常用于停止(或通知)在循环中运行的长时间运行的线程。尝试像

这样的东西
while (!Thread.interrupted()) {
    System.out.println("not interrupted");
}
System.out.println("interrupted");
// then exits