How to use Java guava monitor Monitor Thread
Editor to share with you how to use the Java guava monitor monitor thread, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Maven relies on com.google.guava guava 31.0.1-jre code
No, put the code on the crap.
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: * Monitor Runner @ Version: V1.0 * / public class MonitorRunner implements Runnable {private T param Private Function condition; private Runnable runnable; private Monitor monitor; / * constructor * * @ param param judgment parameter * @ param condition decision function * @ param runnable execution content * / 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 ("thread start"); 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 thread needs to execute System.out.println ("it's a beautiful day");}); executorService.submit (monitorRunner); while (monitorRunner.getParam ())