日期:2014-05-20  浏览次数:20627 次

问一个线程中断的问题,结束阻塞后,线程为什么不接着执行呢
直接上代码
public class InterruptDemo
{

public static void main(String[] args)
{

Thread thread1 = new Thread(new Runnable()
{

public void run()
{

try
{
Thread.sleep(1000);
System.out.println("I'm back");
}
catch (InterruptedException e)
{
System.out.println("I'm interrupted!!");
// e.printStackTrace();
}
}
});

thread1.start();
thread1.interrupt(); // 清除了所有的中断状态即
}
}
我的理解是如果执行了thread1.interrupt();应该打印 I'm interrupted!! 接着打印
I'm back,因为方法不是结束了阻塞吗,可现在的情况是只打印了I'm interrupted!!
在网上查了半天,觉得都说得含含糊糊,请大家指点一下,为什么不会打印出I'm back

谢谢

------解决方案--------------------
略微修改了一下你的代码,你试着执行一下,也许对你理解有帮助:

public class InterruptDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(1000); 
                    System.out.println("I'm not interrupted!");
                } catch (InterruptedException e) {
                    System.out.println("I'm interrupted!");
                }
                System.out.println("I'm back!");
            }
        });

        thread1.start();
        
        int delay = 400;
        //int delay = 1400;
        try {
            Thread.sleep(delay); 
        } catch (InterruptedException e) {
        }
        
        thread1.interrupt(); 
    }
}


如果 delay = 400,打印结果是

I'm interrupted!
I'm back!

因为 InterruptedException 发生在 Thread.sleep(1000) 处,后面的 System.out.println("I'm not interrupted!") 被跳过,执行直接进入 catch 的部分。


如果 delay = 1400,打印结果是

I'm not interrupted!
I'm back!

因为在 Thread.sleep(1000)中,InterruptedException 没有发生。