我正在尝试学习线程中断以及如何在不调用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
我无法理解为什么睡觉打印第二次打断异常被抛出,而不是第一再寄一次检查了下volatile关键字用来帖子第二次停止java.but中的线程,但我无法理解在这种情况下如何使用该线程,因为线程被中断停止。