为什么需要两阶段终止设计模式:
在主线程里创建了临界区对象,主线程里创建了一个线程t1去访问临界区,而临界区里面有一个监控线程(在t1访问临界区调用创建监控线程的方法)当我们需要在另外一个线程里(我的代码里是主线程)想要结束监控线程,那么就调用结束方法去结束监控线程。至于如何结束临界区中的监控线程因为stop方法已经废弃,而interupt也不是终止线程,所以这时我们就需要两阶段终止设计模式,来终止监控线程。
监控线程可以用来监控临界区的各种
普通的两阶段终止设计模式
public class Demotest {
public static void main(String[] args) throws InterruptedException {
ThreadMonitor threadMonitor=new ThreadMonitor();
threadMonitor.start();
Thread.sleep(3000);//让主线程睡一会
threadMonitor.stop();
}
}
class ThreadMonitor{
private Thread mnoitor;
//启动被监控的线程
public void start(){
mnoitor=new Thread(()->{
while (true){
Thread nowthread=Thread.currentThread();//获取当前线程
if (nowthread.isInterrupted()){//有被打断则调用stop方法
break;
}
try {
nowthread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
nowthread.interrupt();//设置打断标志为true
System.out.println("设置了打断标记");
}
}
});
mnoitor.start();
}
//想要停止线程
public void stop(){
mnoitor.interrupt();
}
}
用volatile改进后的两阶段终止设计模式
public class Test_TwoModelStop {
public static void main(String[] args) throws InterruptedException {
ShareClass shareClass1=new ShareClass();
new Thread(()->{
shareClass1.startmonitorthread();
}).start();
Thread.sleep(10);
shareClass1.stopmonitorthread();
}
}
class ShareClass{
private volatile boolean stopflag=false;
private Thread montiorthread;
public void startmonitorthread(){
montiorthread=new Thread(()->{
while (true){
if (stopflag){
System.out.println("料理后事");
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
},"montiorthread");
montiorthread.start();
}
public void stopmonitorthread(){
stopflag=true;
montiorthread.interrupt();//这里是让监控线程加入还在睡眠那么就可以结束睡眠,节省时间
}
}
两阶段终止设计模式还可以用犹豫模式进行优化,这个在我的另外一篇博客
犹豫模式