您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
小编给大家分享一下Java guava monitor监视器线程怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>31.0.1-jre</version> </dependency>
不废话上代码。
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 MonitorRunner<T> implements Runnable { private T param; private Function<T, Boolean> condition; private Runnable runnable; private Monitor monitor; /** * 构造函数 * * @param param 判断参数 * @param condition 判定函数 * @param runnable 执行内容 */ public MonitorRunner(T param, Function<T, Boolean> 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<T> setParam(T param) { this.param = param; return this; } public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(10, new CustomizableThreadFactory("MONITOR-")); MonitorRunner<Integer> 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。
执行结果
以上是“Java guava monitor监视器线程怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。