兩階段終止模式

calong發表於2021-06-08

兩階段終止模式

Two-Phase Termination Patter

描述:使監控執行緒優雅的終止其他正在執行的工作執行緒

程式碼實現:

class TwoPhaseTermination {

    private Thread monitor;

    public void start () {

        monitor = new Thread(() -> {
            while (true) {
                Thread thread = Thread.currentThread();
                if (thread.isInterrupted()) {
                    // TODO: 執行緒終止前的操作
                    System.out.println("Thread is interrupting...");
                    break;
                }
                try {
                    // TODO: 執行緒執行的業務程式碼
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    thread.interrupt();
                }
            }
            System.out.println("Thread was interrupted");
        }, "monitor");
        monitor.start();
    }

    public void stop () {

        monitor.interrupt();
    }
}

測試程式碼:

public class TwoPhaseTerminationTest {

    public static void main(String[] args) {

        TwoPhaseTermination pattern = new TwoPhaseTermination();
        pattern.start();

        try {
            TimeUnit.SECONDS.sleep(2);
            pattern.stop();
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

執行結果:

兩階段終止模式

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章