停止一个线程的主要机制是中断,中断并不代表强迫终止一个线程,
它是一种协作机制,是给线程传递一个取消的信号,
但是让线程来决定如何以及何时退出。
出现死锁,interrupt无法中断
package demo.thread;
public class ThreadTest {
/**
* 完全中止线程 -正确做法
*
* 如果线程里面出现死锁并一直处于等待 interrupt就 中止不了了
*/
private static volatile boolean threadSwitch = true;
private static Object lock =new Object();
public static void main(String[] args) throws InterruptedException {
//业务线程
Thread t = new Thread(()->{
int count = 0;
while (threadSwitch && count<5) {//停止线程内部循环开关
try {
//Thread.sleep(1000*2); //模拟阻塞线程
synchronized (lock){
System.out.println("开始等待");
Thread.currentThread().wait(2000);
System.out.println("等待完了");
}
} catch (Exception e) {
System.out.println("isInterrupted状态:"+Thread.currentThread().isInterrupted());
e.printStackTrace();
}
if(threadSwitch){//双重验证,中止后,立马不再执行其它业务代码
System.out.println(count++);
}
}
});
synchronized (lock){
t.start();
Thread.sleep(5000);
//验证线程已正常启动
System.out.println("1isAlive:"+t.isAlive());
System.out.println("1isInterrupted:"+t.isInterrupted());
//关闭线程
threadSwitch = false;//关闭循环
t.interrupt();// 防止循环内部有阻塞- 在有阻塞的情况下,会抛错出来
System.out.println("2isAlive:"+t.isAlive());
System.out.println("2isInterrupted:"+t.isInterrupted());
Thread.sleep(1000);
System.out.println("3isAlive:"+t.isAlive());
System.out.println("3isInterrupted:"+t.isInterrupted());
t.join();
}
}
}
打印结果:
1isAlive:true
1isInterrupted:false
2isAlive:true
2isInterrupted:true
3isAlive:true
3isInterrupted:true
如果是有阻塞线程 是可以通过interrupt中断的
package demo.thread;
public class ThreadTest {
/**
* 完全中止线程 -正确做法
*
* 如果线程里面出现死锁并一直处于等待 interrupt就 中止不了了
*/
private static volatile boolean threadSwitch = true;
private static Object lock =new Object();
public static void main(String[] args) throws InterruptedException {
//业务线程
Thread t = new Thread(()->{
int count = 0;
while (threadSwitch && count<5) {//停止线程内部循环开关
try {
Thread.sleep(1000*2); //模拟阻塞线程
/*synchronized (lock){
System.out.println("开始等待");
Thread.currentThread().wait(2000);
System.out.println("等待完了");
}*/
} catch (Exception e) {
System.out.println("isInterrupted状态:"+Thread.currentThread().isInterrupted());
e.printStackTrace();
}
if(threadSwitch){//双重验证,中止后,立马不再执行其它业务代码
System.out.println(count++);
}
}
});
//synchronized (lock){
t.start();
Thread.sleep(5000);
//验证线程已正常启动
System.out.println("1isAlive:"+t.isAlive());
System.out.println("1isInterrupted:"+t.isInterrupted());
//关闭线程
threadSwitch = false;//关闭循环
t.interrupt();// 防止循环内部有阻塞- 在有阻塞的情况下,会抛错出来
System.out.println("2isAlive:"+t.isAlive());
System.out.println("2isInterrupted:"+t.isInterrupted());
Thread.sleep(1000);
System.out.println("3isAlive:"+t.isAlive());
System.out.println("3isInterrupted:"+t.isInterrupted());
t.join();
//}
}
}
打印结果:
0
1
1isAlive:true
1isInterrupted:false
2isAlive:true
2isInterrupted:false
isInterrupted状态:false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at demo.thread.ThreadTest.lambda$0(ThreadTest.java:19)
at java.lang.Thread.run(Thread.java:748)
3isAlive:false
3isInterrupted:false
可以看一下下面博主写的很详细