stop()
强制中断线程,可能导致线程中的资源没有释放,比如在try-catch-finally中释放资源,直接中断,不会调用finally块。
new Thread().interrupte()
协作式的中断线程,不会强制中断线程,会发一个interrupt的信号,线程run方法中,如果有Thread.sleep()或者wait,捕获了InterruptedException,会命中该catch, 重置interrupt标记位,如果需要处理该标记位,需要显示调用interrupt(),再判断isInterrupted(),判断run方法执行结束(如:在while循环中,break )。
new Thread().isInterrupted()
线程是否中断的标记位
Thread.interrupted()
静态方法,获取当前线程的中断标记位。调用之后,会重置interrupt标记位,再次通过isInterrupted()获取就为false啦
实战
final Thread thread = new Thread() {
@Override
public void run() {
// while (Thread.interrupted()){
while (!isInterrupted()){
System.out.println("Running");
System.out.println("isInterrupted=" + isInterrupted());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("InterruptedException isInterrupted=" + isInterrupted());
interrupt();
}
}
System.out.println("while end isInterrupted=" + isInterrupted());
}
};
thread.start();
System.out.println("main");
try {
Thread.sleep(30);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}