Java中Thread类的中断方法

时间:2013-06-02 16:18:46

标签: java multithreading interrupt

我有这段代码:

  public void run()
        {
        System.out.println("ciao"); 
        try{
        throw new InterruptedException();
        }catch(InterruptedException ie){ //catch will clear the interrupted status

Thread.currentThread().interrupt();}//it will set back the interrupted status

但是,如果我调用以下方法,请遵循此模式:

Thread1 t1 = new Thread1();//obviously Thread1 extends Thread
        t1.start();

        System.out.println(t1.isInterrupted());

结果是“假”;

另一方面,如果我删除throw new InterruptedException();并尝试从main方法中断它,它会返回我预期的结果:

Thread1 t1 = new Thread1();
        t1.start();
        t1.interrupt();
System.out.println(t1.isInterrupted());

它将返回“true”。

这仅仅是一致性内存问题,或者我在代码中做错了什么? 提前谢谢。

编辑:我编辑了删除方法join()的问题,正如JB Nizet所指出的那样,问题仍然存在。

2 个答案:

答案 0 :(得分:4)

抛出InterrupedException不会设置中断标志。抓住它并不清楚它。

interrupted()是一个静态方法,它告诉当前线程是否被中断。

此外,测试一个线程在加入后是否被中断将始终返回false,因为join()清除了中断标志。

答案 1 :(得分:1)

符合doc

  

按照惯例,任何通过投掷退出的方法   InterruptedException在执行此操作时清除中断状态。然而,   始终可以立即设置中断状态   再次,由另一个线程调用中断。

并且Thread.join抛出InterruptedException