1.定義
我們将線程的正常處理狀态稱為“作業中”,當希望結束這個線程時,則送出“終止請求”。接着,這個線程并不會立刻結束,而是進入“終止進行中”狀态,此時線程還是運作着的,可能處理一些釋放資源等操作。直到終止處理完畢,才會真正結束。
Two-phase Termination主要考慮以下問題:
- 安全地限制(安全性)
- 一定會進行終止處理(生命性)
- 收到“終止請求”後,要盡快進行終止處理(響應性)

2.例子
(1)Counter
public class Counter extends Thread {
private volatile boolean terminated = false;
private int counter = 0;
private Random random = new Random();
@Override
public void run() {
try {
while (!terminated) {
System.out.println("Current counter: " + counter++);
Thread.sleep(random.nextInt(1000));
}
}catch(InterruptedException e){
} finally{
doClean();
}
}
private void doClean() {
System.out.println("Do clean....");
System.out.println("Done");
}
public void close(){
this.terminated = true;
}
}
(2)CountClient
public class CountClient {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
counter.start();
TimeUnit.SECONDS.sleep(10);
counter.close();
}
}