1.Interrupt方式实现
注意:sleep(),wait(),join()方法被interrupt()方法打断之后,isInterrupted()会被重新赋值为false。正常执行的线程如果被interrupt()方法打断,isinterrupted()返回值为true。
代码实现:
public class TwoStageTermination {
public Thread monitor;
public void start() {
monitor = new Thread(){
@Override
public void run() {
Thread thread = Thread.currentThread();
while(true){
if(thread.isInterrupted()){
System.out.println("线程进行结束线程操作。。。。。。。");
break;
}
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("线程开始进行监控操作。。。。。。。");
} catch (InterruptedException e) {
thread.interrupt(); //重新赋值为true
e.printStackTrace();
}
}
}
};
monitor.start();
}
public void stop(){
monitor.interrupt();
}
public static void main(String[] args) {
TwoStageTermination tst = new TwoStageTermination();
tst.start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
tst.stop();
}
}