中止线程有三种方式分别是,自然中断、stop、中断。他们区别分别为:
线程自然终止:要么是 run 执行完成了,要么是抛出了一个未处理的异常导致线程提前结束。
stop:暂停、恢复和停止操作对应在线程 Thread 的 API 就是 suspend()、resume()和 stop()。但是这些 API 是过期的,也就是不建议使用的。不建议使用的原因主要有:以 suspend()方法为例,在调用后,线程不会释放已经占有的资源(比如锁),而是占有着资源进入睡眠状态,这样容易引发死锁问题。
中断:安全的中止则是其他线程通过调用某个线程 A 的 interrupt()方法对其进行中断操作, 中断好比其他线程对该线程打了个招呼,“A,你要中断了”,不代表线程 A 会立即停止自己的工作,同样的 A 线程完全可以不理会这种中断请求。因为 java 里的线程是协作式的,不是抢占式的。线程通过检查自身的中断标志位是否被置为 true 来进行响应,其使用方式如下:
线程通过方法 isInterrupted()来进行判断是否被中断,也可以调用静态方法Thread.interrupted()来进行判断当前线程是否被中断,不过 Thread.interrupted()会同时将中断标识位改写为 false。
下面使用interrupted和isInterrupted演示并展示其结果:
public class EndThread {
private static class UseThread extends Thread{
public UseThread(String name) {
super(name);
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName+" interrrupt flag ="+isInterrupted());
while(!isInterrupted()){
//while(!Thread.interrupted()){
//while(true){
System.out.println(threadName+" is running");
System.out.println(threadName+"inner interrrupt flag ="
+isInterrupted());
}
System.out.println(threadName+" interrrupt flag ="+isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
Thread endThread = new UseThread("endThread");
endThread.start();
Thread.sleep(20);
endThread.interrupt();//中断线程,其实设置线程的标识位true
}
}
使用isInterrupted运行结果:
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread interrrupt flag =true
.............finally
使用interrupted运行结果:
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =false
endThread is running
endThreadinner interrrupt flag =true
endThread interrrupt flag =false