Java线程中断:中断()vs停止()
我在Java中使用线程时遇到问题。在Java中,中断线程时,中断()和停止()之间的首选方法是什么?为什么Java线程中断:中断()vs停止(),java,multithreading,methods,interruption,Java,Multithreading,Methods,Interruption,我在Java中使用线程时遇到问题。在Java中,中断线程时,中断()和停止()之间的首选方法是什么?为什么 谢谢你的回复 理论上,按照您提出问题的方式,无论是哪种方式,线程都不应该通过同步标志自行理解何时必须终止 这是通过使用interrupt()方法来实现的,但是您应该了解,只有当线程处于等待/休眠状态(在本例中引发异常)时,这种方法才会“起作用”,否则您必须在线程的run()方法内检查自己线程是否中断(使用isInterrupted()method),并在需要时退出。例如: public c
谢谢你的回复 理论上,按照您提出问题的方式,无论是哪种方式,线程都不应该通过同步标志自行理解何时必须终止 这是通过使用
interrupt()
方法来实现的,但是您应该了解,只有当线程处于等待/休眠状态(在本例中引发异常)时,这种方法才会“起作用”,否则您必须在线程的run()方法内检查自己线程是否中断(使用isInterrupted()
method),并在需要时退出。例如:
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()
在Java8中已被弃用,因此我想说Thread.interrupt()
是一种方法。上面有一个冗长的解释。它还提供了如何使用线程的一个很好的示例。您阅读了文档吗?该链接提供了许多在无限周期内干扰InterruptedException的示例。这是处理这些问题的正确方法,还是仅用于说明Thread.stop()的复杂性?我会这样做。基本上,您可以从某个顶层启动关闭,然后它向下传播,中断并标记所有线程停止(从一个无限周期开始),并让它们以可控的方式终止。Thread.stop()
已被弃用十多年了。Java8和早期版本的区别在于Thread.stop(Throwable)
立即抛出不支持操作。