public T get()throws InterruptedException { lock.lock(); try { while (value == null) { valuePresent.await(); } T result = value; value = null; valueAbsent.signal(); return result; } finally { lock.unlock(); } } }
// 3. 使用 Guava 提供的 Monitor,内部使用了 ReentrantLock,写法上更灵活,不再需要手写 while 循环 publicclassSafeBox<T> { privatefinal Monitor monitor = new Monitor(); privatefinal Monitor.Guard valuePresent = new Monitor.Guard(monitor) { publicbooleanisSatisfied(){ return value != null; } }; privatefinal Monitor.Guard valueAbsent = new Monitor.Guard(monitor) { publicbooleanisSatisfied(){ return value == null; } }; private T value;
public T get()throws InterruptedException { monitor.enterWhen(valuePresent); try { T result = value; value = null; return result; } finally { monitor.leave(); } }
Copyright Declaration: This station is mainly used to sort out incomprehensible knowledge. I have not fully mastered most of the content. Please refer carefully.