【发布时间】:2014-05-27 00:23:53
【问题描述】:
在 Java 中使用线程时遇到问题。在 Java 中中断线程时,interrupt() 和 stop() 之间首选的方法是什么?为什么?
感谢您的任何回复。
【问题讨论】:
-
您阅读文档了吗?
标签: java multithreading methods interruption
在 Java 中使用线程时遇到问题。在 Java 中中断线程时,interrupt() 和 stop() 之间首选的方法是什么?为什么?
感谢您的任何回复。
【问题讨论】:
标签: java multithreading methods interruption
从理论上讲,按照您提出问题的方式,线程应该通过同步标志自行理解何时必须终止。
这是通过使用interrupt() 方法完成的,但您应该了解,只有当您的线程处于等待/睡眠状态(并且在这种情况下会引发异常)时,这才“有效”,否则您必须检查你自己,在你的线程的 run() 方法中,如果线程被中断(使用isInterrupted() 方法),并在你想要的时候退出。例如:
public class Test {
public static void main(String args[]) {
A a = new A(); //create thread object
a.start(); //call the run() method in a new/separate thread)
//do something/wait for the right moment to interrupt the thread
a.interrupt(); //set a flag indicating you want to interrupt the thread
//at this point the thread may or may not still running
}
}
class A extends Thread {
@Override
public void run() { //method executed in a separated thread
while (!this.isInterrupted()) { //check if someone want to interrupt the thread
//do something
} //at the end of every cycle, check the interrupted flag, if set exit
}
}
【讨论】:
Thread.stop() 在 java 8 中已被弃用,所以我想说Thread.interrupt() 是要走的路。 oracles site 有一个冗长的解释。它还提供了一个很好的例子来说明如何使用线程。
【讨论】:
Thread.stop() 已被弃用十多年了。 Java 8 和更早版本的区别在于Thread.stop(Throwable) 现在抛出UnsupportedOperation。