Semaphore
import java.util.concurrent.Semaphore;
class H2O {
Semaphore sh = new Semaphore(2);
Semaphore so = new Semaphore(0);
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
sh.acquire();
// releaseHydrogen.run() outputs "H". Do not change or remove this line.
releaseHydrogen.run();
so.release();
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
so.acquire(2);
// releaseOxygen.run() outputs "O". Do not change or remove this line.
releaseOxygen.run();
sh.release(2);
}
}
ReentantLock
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class H2O {
ReentrantLock lock = new ReentrantLock();
Condition c = lock.newCondition();
int h = 0;
int o = 0;
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
lock.lock();
try {
while (h == 2) {
c.await();
}
h++;
if (h == 2 && o == 1) {
h = 0;
o = 0;
}
releaseHydrogen.run();
c.signalAll();
} finally {
lock.unlock();
}
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
lock.lock();
try {
while (o == 1) {
c.await();
}
o++;
if (h == 2 && o == 1) {
h = 0;
o = 0;
}
// releaseOxygen.run() outputs "O". Do not change or remove this line.
releaseOxygen.run();
c.signalAll();
} finally {
lock.unlock();
}
}
}