2011-11-08 31 views
5

我想中断一个线程,但调用中断()似乎不工作,下面是示例代码:为什么中断()无法按预期工作,它是如何工作

public class BasicThreadrRunner { 
    public static void main(String[] args) { 
     Thread t1 = new Thread(new Basic(), "thread1"); 
     t1.start(); 
     Thread t3 = new Thread(new Basic(), "thread3"); 
     Thread t4 = new Thread(new Basic(), "thread4"); 
     t3.start(); 
     t1.interrupt(); 
     t4.start(); 
    } 
} 
class Basic implements Runnable{ 
    public void run(){ 
     while(true) { 
      System.out.println(Thread.currentThread().getName()); 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       System.err.println("thread: " + Thread.currentThread().getName()); 
       //e.printStackTrace(); 
      } 
     } 
    } 
} 

,但输出的样子thead1仍在运行。所以,任何人都可以解释它,()的作品,如何中断感谢

回答

12

因为你赶上InterruptedException线程仍在只需运行和保持运行。 interrupt()主要是设置一个标志在Thread对象,你可以用isInterrupted()检查。这也导致了一些方法 - sleep()joinObject.wait(),尤其是 - 通过抛出InterruptedException立即返回。它也会导致一些I/O操作立即终止。如果您发现您的catch块打印出来,然后你可以看到,interrupt()工作。

+0

:感谢您的帮助 – jason

10

正如其他人所说,你赶上中断,但确实与它无关。你需要做的是使用逻辑,例如,

while(!Thread.currentThread().isInterrupted()){ 
    try{ 
     // do stuff 
    }catch(InterruptedException e){ 
     Thread.currentThread().interrupt(); // propagate interrupt 
    } 
} 

使用循环逻辑,如while(true)只是懒惰的编码传播中断。相反,轮询线程的中断标志以确定通过中断终止。

+0

或者您可以将try/catch移到循环之外。 ;) –

+2

是的,但那已经由@MByD提到的,是它让坏的循环逻辑不变。 :D – mre

+0

@mre:谢谢你的亲友 – jason

相关问题