1、导入依赖:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency>
2、案例
import com.google.common.util.concurrent.Monitor; import static java.lang.Thread.currentThread; /** * @create 2021-02-14 22:07 * @desc Guava之Monitor 补充说明1: Monitor 当某个线程进入 Monitor 代码块的时候,实际上它首先要抢占与 Monitor 关联的 Lock , 当该线程调用了 leave() ,实际上是需要释放与 Monitor 关联的 Lock ,因此在某个时刻 仅有一个线程能够进入到 Monitor 代码块中(排他的)。 补充说明2: Monitor 隐藏了锁的获取、临界值判断 、 线程挂起 、阻塞线程唤醒、锁的释放等。 **/ public class MonitorExample { //定义 Monitor 对象 private static Monitor monitor = new Monitor(); //共享数据 private static int x = 0; //定义临界值,共享数据的值不能超过 MAX_VALUE private static final int MAX_VALUE = 10; // 定义 Guard 并且实现 isSatisfied() private static final Monitor.Guard INC_WHEN_LESS_10 = new Monitor.Guard(monitor) { // 此方法内部编写的是对临界值的判断逻辑,相当于在写对象监视器或者 Condition 时的临界值判断逻辑 @Override public boolean isSatisfied() { return x < MAX_VALUE; } }; public static void main(String[] args) throws InterruptedException { while(true) { /** * monitor.enterWhen() 该方法除了“具备锁的功能”之外,还“具备临界值判断的操作”。 * * 只有满足临界值的判断,才会执行后续的流程。如果不满足临界值的判断,当前线程会进入“阻塞队列” * (其实在 Guard 内部使用的也是 Condition ) */ monitor.enterWhen(INC_WHEN_LESS_10); try { x++; System.out.println(currentThread() + ": x value is" + x); } finally { /** * monitor.leave() 该方法除了释放当前的锁之外,还会通知唤醒与 Guard 关联的 Condition * 阻塞队列中的某个阻塞线程 。 */ monitor.leave(); } } } }