Java guava monitor监视器线程的使用详解

网友投稿 300 2022-09-18


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 MonitorRunner implements Runnable {

private T param;

private Function condition;

private Runnable runnable;

private Monitor monitor;

/**

* 构造函数

*

* @param param 判断参数

* @param condition 判定函数

* @param runnable 执行内容

*iUiUbk/

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 executorServiciUiUbke =

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。

执行结果

总结

没啥好总结的,看场景使用吧。

如果本文对你有用,请点个赞吧,谢谢。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:华为设备配置PIM-DM基本网络(华为pim ssm配置)
下一篇:华为设备配置PIM-SM命令(华为交换机配置)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~