在 Java 中使用线程时遇到问题。在 Java 中中断线程时,interrupt() 和 stop() 之间首选的方法是什么?为什么?
感谢您的任何回复。
在 Java 中使用线程时遇到问题。在 Java 中中断线程时,interrupt() 和 stop() 之间首选的方法是什么?为什么?
感谢您的任何回复。
从理论上讲,按照您提出问题的方式,线程应该通过同步标志自行理解何时必须终止。
这是通过使用该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 网站上有一个冗长的解释。它还提供了一个很好的例子来说明如何使用线程。