🌕 🌗 1117. H2O 生成

吞佛童子2022年6月20日
  • algorithm
  • thread
小于 1 分钟

🌕 🌗 1117. H2O 生成

难度: 🌕 🌗

问题描述

img_1.png


解法 - Semaphore

class H2O {
    Semaphore so;
    Semaphore sh;

    public H2O() {
        this.so = new Semaphore(0); 
        this.sh = new Semaphore(2);
    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
		sh.acquire();
        releaseHydrogen.run();
        so.release();
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        so.acquire(2);
        releaseOxygen.run();
        sh.release(2);
    }
}

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou