最近剛開始學線程。
任務
使用sleep,interrupt實現
import org.apache.log4j.Logger;
import static java.lang.Thread.sleep;
public class Demo{
public static void main(String[] agrs) throws InterruptedException {
TwoPhaseTerminate pt=new TwoPhaseTerminate();
pt.start();
//分給monitor線程時間片後,monitor開始運行。
//此時main和monitor線程並行
Thread.sleep(5000);//main線程睡眠5s,monitor還在運行
pt.stop();//main睡眠結束,調用結束方法。線程monitor結束
}
}
class TwoPhaseTerminate{
private static Logger logger = Logger.getLogger(TwoPhaseTerminate.class);
private Thread monitor;
public void start(){
monitor=new Thread(()->{
while(true){
Thread current= Thread.currentThread();
if(current.isInterrupted()){
logger.debug("退出監控");
break;
}
try {
Thread.sleep(2000);//state 1:這裏打斷,打斷標記會被清除
logger.debug("監控中");//state 2:在這裏打斷沒事。
} catch (InterruptedException e) {
e.printStackTrace();
current.interrupt();
//鑑於state 1,在睡眠時打斷,標記會被清除
//所以可以在打斷一次。這樣打斷標記就是true
//沒有這一句的話,線程會一直運行下去。(不考慮main線程的睡眠時間,
//因爲可能剛好在state 2 打斷。
}
}
},"monitor");
monitor.start();//main線程調用
}
public void stop(){
monitor.interrupt();
}
}
結果如下