1117. H2O 生成
1.题目分析——信号量解法
- 每次生产h的线程先执行,每次hSema.acquire(); hSema信号量-1,同时oSema信号量+1;
- 2次生产h之后,hSema用完,oSema增加到2,oSema.acquire(2)需要2个信号量,此时才能执行生产o,生产完oSema变为0
- 生产1次o,之后,hSema信号量通过hSema.release(2);方法增加到2.
2.代码
class H2O {
private Semaphore hSema = new Semaphore(2);
private Semaphore oSema = new Semaphore(0);
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
hSema.acquire();
releaseHydrogen.run();
oSema.release();
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
oSema.acquire(2);
releaseOxygen.run();
hSema.release(2);
}
}
1.解题思路——synchronized + h原子的数量判断条件
class H2O {
private int h_count = 0;
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
synchronized (this) {
h的生产数量为2时阻塞 ,去生产o
while (h_count>=2)
this.wait();
h_count++;
// releaseHydrogen.run() outputs "H". Do not change or remove this line.
releaseHydrogen.run();
this.notifyAll();
}
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
synchronized (this) {
h的生产数量不到2时阻塞, 继续去生产h
while (h_count < 2)
this.wait();
// releaseOxygen.run() outputs "O". Do not change or remove this line.
releaseOxygen.run();
h_count = 0;
this.notifyAll();
}
}
}