Java高并发编程学习--6. 线程的关闭
一、捕获interrupt关闭线程
package mian;
import java.util.concurrent.TimeUnit;
/**
* @ClassName InterruptThreadExit
* @Description TODO
* JDK有一个Deprecated方法stop,但是该方法有一个问题
* 该方法关闭线程时可能不会释放monitor的锁
* 1. 捕获interrupt关闭线程
* 2. volatile开关控制
* @Author Cays
* @Date 2019/3/11 10:56
* @Version 1.0
**/
public class InterruptThreadExit {
public static void main(String []args) throws InterruptedException {
Thread t=new Thread(){
@Override
public void run() {
System.out.println("I will start work.");
while (!isInterrupted()){
//System.out.println("working...");
}
System.out.println("I will be exiting.");
}
};
t.start();
TimeUnit.SECONDS.sleep(5);
System.out.println("System will be shutdown.");
t.interrupt();
//通过检查线程interrupt标识来决定是否退出
//执行可中断方法,可捕获中断信号退出
}
}
执行结果:
二、volatile开关控制
package mian;
import java.util.concurrent.TimeUnit;
/**
* @ClassName FlagThreadExit
* @Description TODO
* volatile开关控制
* @Author Cays
* @Date 2019/3/11 11:03
* @Version 1.0
**/
public class FlagThreadExit {
static class MyTask extends Thread{
private volatile boolean close=false;
//volatile是java原子变量以及并发包的基础
@Override
public void run() {
System.out.println("I will start work");
while (!close&&!isInterrupted());
System.out.println("I will be exit.");
}
public void close(){
this.close=true;
this.interrupt();
}
}
public static void main(String []args) throws InterruptedException {
MyTask t=new MyTask();
t.start();
TimeUnit.SECONDS.sleep(3);
System.out.println("System will be shutdoewn.");
t.close();
}
}
执行结果: