在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
}
}