Guava之Monitor

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();
         }
      }
   }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小达人Fighting

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值