最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Java guava monitor监视器线程代码使用解析
时间:2022-06-29 02:06:10 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Java guava monitor监视器线程代码使用解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
Maven依赖
com.google.guava guava 31.0.1-jre
代码
package com.huyi.csdn.tools; import cn.hutool.core.thread.ThreadUtil; import com.google.common.util.concurrent.Monitor; import org.springframework.scheduling.concurrent.CustomizableThreadFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Function; /** * @Program: csdn @ClassName: MonitorRunner @Author: huyi @Date: 2021-10-30 15:22 @Description: * 监视器Runner @Version: V1.0 */ public class MonitorRunnerimplements Runnable { private T param; private Function condition; private Runnable runnable; private Monitor monitor; /** * 构造函数 * * @param param 判断参数 * @param condition 判定函数 * @param runnable 执行内容 */ public MonitorRunner(T param, Function condition, Runnable runnable) { this.param = param; this.condition = condition; this.runnable = runnable; monitor = new Monitor(); } @Override public void run() { System.out.println("线程开始"); Monitor.Guard guard = new Monitor.Guard(monitor) { @Override public boolean isSatisfied() { return condition.apply(param); } }; while (true) { if (monitor.enterIf(guard)) { try { runnable.run(); } finally { monitor.leave(); break; } } else { continue; } } } public T getParam() { return param; } public MonitorRunner setParam(T param) { this.param = param; return this; } public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(10, new CustomizableThreadFactory("MONITOR-")); MonitorRunner monitorRunner = new MonitorRunner<>( 0, x -> x > 10, () -> { // todo 线程需要执行的内容 System.out.println("今天天气真好"); }); executorService.submit(monitorRunner); while (monitorRunner.getParam() <= 10) { monitorRunner.setParam(monitorRunner.getParam() + 1); ThreadUtil.sleep(1000L); System.out.println("当前Param的值:" + monitorRunner.getParam()); } ThreadUtil.sleep(5000L); executorService.shutdown(); } }
代码说明
主要在构造对象的时候需要传递泛型的校验对象,以及断言和需要执行的Runable。
执行结果
相关文章
- 《无限暖暖》天星之羽获得位置介绍 12-20
- 《流放之路2》重铸台解锁方法介绍 12-20
- 《无限暖暖》瞄准那个亮亮的成就怎么做 12-20
- 《无限暖暖》魔气怪终结者完成方法 12-20
- 《无限暖暖》曙光毛团获得位置介绍 12-20
- 《无限暖暖》日光果获得位置介绍 12-20