1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class Test3{ public static void main(String[] args){ TwoPhaseTermination tpt = new TwoPhaseTermination(); tpt.start(); Thread.sleep(3500); tpt.stop(); } }
class TwoPhaseTermination{ private Thread monitor; public void start(){ monitor = new Thread(() -> { while(true){ Thread current = Thread.currentThread(); if(current.isInterrupted()){ log.debug("料理后事"); break; } try{ Thread.sleep(1000); log.debug("执行监控记录"); }catch (InterruptedException e){ e.printStackTrace(); current.interrupt(); } } }); monitor.start(); } public void stop(){ monitorThread.interrupt(); } }
|