https://leetcode.cn/problems/building-h2o/
有一个多线程来生成 h2o 的题目。有很多种解法。
我的思路是:信号量+锁。
在一个 h2o 内部,通过信号量来控制入口,这样能并发。比如,2个h,在2个线程中可以各自自由执行。
内部的做完了,要通过锁这个屏障才能到下一个 h2o,起到同步的作用。2个h与1个o完成后,要等待比例核对。
我按照这个思路写了,但是一直通不过。
感兴趣的,可以帮忙看看,指点。
我的代码
代码片段
class H2O {
//controls between different h2o
private final Object lock = new Object();
private volatile AtomicInteger hy_count = new AtomicInteger(0);
private volatile AtomicInteger ox_count = new AtomicInteger(0);
//controls inside a h2o
private Semaphore hy_2entry = new Semaphore(2);
private Semaphore ox_1entry = new Semaphore(1);
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
hy_2entry.acquire();
//work stuff
releaseHydrogen.run();
hy_count.incrementAndGet();
if(hy_count.get()>1){
synchronized(lock){
while(ox_count.get()<1)
lock.wait();
ox_count.getAndAdd(-1);
hy_2entry.release(2);
lock.notifyAll();
}
}
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
ox_1entry.acquire();
//work stuff
releaseOxygen.run();
ox_count.incrementAndGet();
if(ox_count.get()>0){
synchronized(lock){
while(hy_count.get()<2)
lock.wait();
hy_count.getAndAdd(-2);
ox_1entry.release();
lock.notifyAll();
}
}
}
}最后,感谢您抽空阅读!