interrupt()不起作用

我试图在以下代码中终止线程:

public synchronized void run() { try { while (!Thread.currentThread().isInterrupted()) { this.scan(); this.distribute(); this.wait(); } } catch (InterruptedException e) {} } public void cancel() { this.interrupt(); } 

但线程不会终止。 我使用调试器this.interrupt()现在命令this.interrupt() ,线程没有被中断(我在表达式上this.isInterrupted()并且它保持为false )。 任何人都知道为什么这个线程不会被打断?

编辑:

问题已经找到。 原来这个线程有两个实例。 我附上导致这个问题的有问题的代码:

 /* (class Detector extends Thread) */ Detector detector = new Detector(board); ... Thread tdetector = new Thread(detector); /* WRONG!!! */ ... tdetector.start(); ... 

根据文档 ,如果在线程处于wait()状态时调用interrupt() ,则不会设置中断标志。 你应该得到一个中断的exception,它将退出循环(和线程)。

编辑

根据我的评论和您的回复,问题是您运行了多个这些线程。

你可能在错误的线程上调用cancel 。 如果你看它,它cancel()取消这个线程 。 你可能想要取消一些其他线程。

您对isInterrupted()调用也是不必要的,但这不会导致中断丢失……


另一方面,如果cancel方法是扩展Thread的类的方法,那么this可能是需要取消的线程。 (我们这些人试图回答的问题是原始问题中的细节不够……)