概述
“分兩個階段終止”的意思是一先執行完終止處理再終止線程的模式,通俗的比喻是“先收拾房間再睡覺”。
線程進行正常處理時的狀態為“操作中”。要停止該線程,我們會發出“終止請求”。這樣,線程就不會突然終止,而是先開始進行“打掃工作”。我們稱這種狀態為“終止處理中”。
從“操作中”變為“終止處理中”是線程終止的第一個階段。
在”終止處理中“狀態下,線程不會再進行正常操作了。它雖然仍然在運行,但是只進行終止處理。終止處理完成后,就會真正地終止線程。”終止處理中“狀態結束是線程終止的第二階段。
先從”操作中“狀態變為”終止處理中“狀態,然后再真正地終止線程。這就是Two-Phase Termination模式。
示例程序
- CountupThread 表示進行技術的線程類
- Main 測試程序行為的類
CountupThread 類
public class CountupThread extends Thread {
private long counter = 0;
private volatile boolean shutdownRequested = false;
public void shutdownRequest() {
shutdownRequested = true;
interrupt();
}
public boolean isShutdownRequested(){
return shutdownRequested;
}
public final void run() {
try{
while(!isShutdownRequested()){
doWork();
}
} catch (InterruptedException e){
} finally { doShutdown();}
}
private void doWork() throws InterruptedException {
counter++;
System.out.println("doWork: counter = " + counter);
Thread.sleep(500);
}
private void doShutdown(){
System.out.println("doShutdown: counter = " + counter);
}
}
Main 類
public class Main {
public static void main(String[] args){
System.out.println("main: BEGIN");
try{
//啟動線程
CountupThread t = new CountupThread();
t.start();
//稍微間隔一段時間
Thread.sleep(1000);
//線程的終止請求
System.out.println("main: shutdownRequest");
t.shutDownRequest();
System.out.println("main: shutdownRequest");
System.out.println("main: join");
//等待線程終止
t.join();
} catch(InterruptedException e){
e.printStackTrace();
};
System.out.println("main: END");
}
}
Two Phase Termination 模式的角色
- TerminationRequester(終止請求發出者)
- Terminator (終止者)