问一个线程中断的问题,结束阻塞后,线程为什么不接着执行呢

toss2000 2013-03-22 05:32:54
直接上代码
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

谢谢
...全文
250 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
jswatcher 2013-03-23
  • 打赏
  • 举报
回复
略微修改了一下你的代码,你试着执行一下,也许对你理解有帮助:

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 没有发生。
toss2000 2013-03-23
  • 打赏
  • 举报
回复
谢谢jswatcher,的确是高手!膜拜!!
fyskycn 2013-03-22
  • 打赏
  • 举报
回复
太复杂了 看不懂啊
龙四 2013-03-22
  • 打赏
  • 举报
回复
楼主复习下异常相关的内容吧,这跟中断没关系
yanxing2012 2013-03-22
  • 打赏
  • 举报
回复
api里讲了这个interrupt()方法的用法: public void interrupt() 中断线程。 如果当前线程没有中断它自己(这在任何情况下都是允许的),则该线程的 checkAccess 方法就会被调用,这可能抛出 SecurityException。 如果线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException。 所以你懂得。。。若你把System.out.println("I'm back");放在Thread.sleep(1000)之前,就会执行System.out.println("I'm back");了。。。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧