我正在尝试学习线程中断以及如何在不调用 stop 的情况下终止线程。
public class Test implements Runnable{
static Thread threadTest=null;
public static void main(String args[]){
System.out.println("Hello i am main thread");
Test thread= new Test();
threadTest= new Thread(thread);
threadTest.start();
}
private static void exitThread() {
threadTest.interrupt();
}
@Override
public void run() {
boolean run = true;
while (run) {
try {
System.out.println("Sleeping");
Thread.sleep((long) 10000);
exitThread();
System.out.println("Processing");
} catch (InterruptedException e) {
run = false;
}
}
}
}
输出
Hello i am main thread
Sleeping
Processing
Sleeping
我无法理解为什么第二次打印 Sleeping 并且第二次而不是第一次抛出中断异常。我检查了使用 volatile 关键字停止 java 线程的帖子。但我无法理解那是怎么回事将在这种情况下使用,因为线程因中断而停止。
最佳答案
为了看到线程被中断而不是第二次进入sleep方法,改变run方法中的while循环测试来检查中断标志:
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println("Sleeping");
Thread.sleep((long) 10000);
exitThread();
System.out.println("Processing");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
线程会 hibernate ,然后设置自己的中断标志,然后检查标志并终止。 InterruptedException 将仅在设置中断标志时线程处于 hibernate 状态时由 Thread#sleep 方法抛出。
不需要您的本地 boolean 变量。如果 Thread#sleep 抛出一个 InterruptedException(在这个例子中它不会因为线程检查中断标志并离开 while 循环)然后中断标志被清除,在 catch block 中恢复它允许 while 测试看到线程被中断。
在实际程序中,线程会被另一个线程中断,线程没有理由中断自身(它可以直接返回)。
关于java - 如何使用线程中断方法停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31895612/