Guava 5 - Concurrency
整理下 Guava 对并发这块的封装。
Monitor
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
public class SafeBox<T> { private T value; public synchronized void set(T newValue) throws InterruptedException { while (value != null) { wait(); } this.value = newValue; notifyAll(); } public synchronized T get() throws InterruptedException { while (value == null) { wait(); } T result = value; value = null; notifyAll(); return result; } }
public class SafeBox<T> { private T value; private final ReentrantLock lock = new ReentrantLock(); private final Condition valuePresent = lock.newCondition(); private final Condition valueAbsent = lock.newCondition();
public void set(T newValue) throws InterruptedException { lock.lock(); try { while (value != null) { valueAbsent.await(); } value = newValue; valuePresent.signal(); } finally { lock.unlock(); } }
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(); } } }
public class SafeBox<T> { private final Monitor monitor = new Monitor(); private final Monitor.Guard valuePresent = new Monitor.Guard(monitor) { public boolean isSatisfied() { return value != null; } }; private final Monitor.Guard valueAbsent = new Monitor.Guard(monitor) { public boolean isSatisfied() { 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(); } }
public void set(T newValue) throws InterruptedException { monitor.enterWhen(valueAbsent); try { value = newValue; } finally { monitor.leave(); } } }
|
Service
Title: Guava 5 - Concurrency
Author: Jiandong
Date: 2018-07-02
Last Update: 2026-06-16
Blog Link: https://mjd507.github.io/2018/07/02/Guava-Guide-5/
Copyright Declaration: Please refer carefully, most of the content I have not fully mastered.