您好,登錄后才能下訂單哦!
小編給大家分享一下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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。