Maven依赖
1
2
3
4
5
|
< dependency > < groupId >com.google.guava</ groupId > < artifactId >guava</ artifactId > < version >31.0.1-jre</ version > </ dependency > |
代码
不废话上代码。
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
|
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监视器线程的使用详解的文章就介绍到这了,更多相关Java 监视器线程内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://huyi-aliang.blog.csdn.net/article/details/121056404