我在Java中使用线程时遇到了一个问题。在Java中,interrupt()和stop()中断线程的首选方法是什么?为什么?
感谢您的回复。
发布于 2014-05-27 00:07:58
从理论上讲,按照您提出问题的方式,线程应该通过同步标志自己理解何时必须终止。
这是通过使用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
}
}发布于 2014-05-27 00:08:04
Thread.stop()已经在Java8中被弃用了,所以我想说Thread.interrupt()是个不错的选择。在oracles site上有一个冗长的解释。它还提供了一个很好的例子来说明如何使用线程。
https://stackoverflow.com/questions/23873972
复制相似问题