前言:学习JUC包后,通过leetcode多线程的题目练习一下,1117-H2O生成
Semaphore
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class H2O { private Semaphore h = new Semaphore(2); private Semaphore o = new Semaphore(0); public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException { h.acquire(); releaseHydrogen.run(); o.release(); }
public void oxygen(Runnable releaseOxygen) throws InterruptedException { o.acquire(2); releaseOxygen.run(); h.release(2); } }
|
CyclicBarrier
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class H2O { private ConcurrentLinkedQueue<Runnable> hQueue = new ConcurrentLinkedQueue<>(); private ConcurrentLinkedQueue<Runnable> oQueue = new ConcurrentLinkedQueue<>(); private CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Runnable() { @Override public void run() { hQueue.poll().run(); hQueue.poll().run(); while (oQueue.isEmpty()) { } oQueue.poll().run(); } });
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException { hQueue.add(releaseHydrogen); try { cyclicBarrier.await(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }
public void oxygen(Runnable releaseOxygen) throws InterruptedException { oQueue.add(releaseOxygen); } }
|
管程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public class H2O { private ReentrantLock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); private volatile int count = 0;
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException { lock.lock(); try { while(count >= 2){ condition.await(); } releaseHydrogen.run(); count++; condition.signalAll(); } finally { lock.unlock(); }
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException { lock.lock(); try { while(count < 2){ condition.await(); } releaseOxygen.run(); count = 0; condition.signalAll(); } finally { lock.unlock(); } } }
|