保護性暫停模式

calong發表於2021-06-08

保護性暫停模式

Guarded Suspension Pattern

執行緒間通訊模型,Future和Promise的實現原理

程式碼實現:

class GuardedSuspension {

    private Object response;

    public Object get () {

        synchronized (this) {

            while (response == null) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
    }

    public void complete (Object response) {

        synchronized (this) {

            this.response = response;
            this.notifyAll();
        }
    }
}

測試程式碼:

public class GuardedSuspensionTest {

    public static void main(String[] args) throws InterruptedException {

        GuardedSuspension pattern = new GuardedSuspension();

        Thread thread = new Thread(() -> {
            System.out.println("等待結果...");
            System.out.println(pattern.get());;
        }, "monitor");

        Thread waiter = new Thread(() -> {
            Integer result = 0;
            try {
                for (int i = 0; i < 10; i++) {
                    result = i++;
                    System.out.println("運算中...");
                    TimeUnit.MILLISECONDS.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("正在生成結果...");
            pattern.complete(result);
        });
        thread.start();
        waiter.start();

        thread.join();
        waiter.join();
    }
}

執行結果:
保護性暫停模式

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

相關文章