代码:
package demo1;
public class StopXiancheng {
public static void main(String[] args) throws InterruptedException {
TwoPhaseTermination tpt=new TwoPhaseTermination();
tpt.start();
Thread.sleep(3500);
System.out.println("停止监控");
tpt.stop();
}
}
class TwoPhaseTermination{
//监控线程
private Thread monitorThread;
private volatile boolean stop=false;
//启动监控线程
public void start(){
monitorThread=new Thread(()->{
while (true){
Thread current=Thread.currentThread();
//是否被打断
if(stop){
System.out.println("料理后事");
break;
}
try {
Thread.sleep(1000);
System.out.println("执行监控");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"monitor");
monitorThread.start();
}
public void stop(){
stop=true;
monitorThread.interrupt();
}
}



