Java guava monitor監視器線程的使用詳解

Maven依賴

        <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監視器線程的使用詳解的文章就介紹到這瞭,更多相關Java 監視器線程內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: