最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何基于ThreadPoolExecutor創(chuàng)建線程池并操作

 更新時(shí)間:2020年11月10日 09:25:26   作者:牛鼻子老趙  
這篇文章主要介紹了如何基于ThreadPoolExecutor創(chuàng)建線程池并操作,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

日常工作中很多地方很多效率極低的操作,往往可以改串行為并行,執(zhí)行效率往往提高數(shù)倍,廢話不多說先上代碼

1、用到的guava坐標(biāo)

<dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>18.0</version>
    </dependency>

2、創(chuàng)建一個(gè)枚舉保證線程池是單例

package com.hao.service;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

public enum ExecutorManager {

  INSTANCE;

  private ExecutorManager() {

  }

  private static int AVAILABLEPROCESSORS = Runtime.getRuntime().availableProcessors();

  public static final ThreadPoolExecutor threadPoolExecutor =
    new ThreadPoolExecutor(AVAILABLEPROCESSORS * 50, AVAILABLEPROCESSORS * 80, 0L, TimeUnit.MILLISECONDS,
      new LinkedBlockingQueue<Runnable>(AVAILABLEPROCESSORS * 2000),
      new ThreadFactoryBuilder().setNameFormat("ExecutorManager-pool-Thread-%d").build());
}

3、創(chuàng)建一個(gè)方法類

package com.hao.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;

@Service
public class ExecutorContext {

  public ExecutorService executorService;
  private int DEFAULT_WAIT_SECONDS = 2;

  @PostConstruct
  public void init() {
    executorService = ExecutorManager.threadPoolExecutor;
  }

  public <T> List<T> waitAllFutures(List<Callable<T>> calls, int milliseconds) throws Exception {
    Preconditions.checkArgument(null != calls && !calls.isEmpty(), "callable empty.");
    LatchedCallables<T> latchAndCallables = wrapCallables(calls);
    List<Future<T>> futurres = new LinkedList<>();
    for (CountdownedCallable<T> callable : latchAndCallables.wrappedCallables) {
      if (null != callable) {
        futurres.add(executorService.submit(callable));
      }
    }
    List<T> rets = new ArrayList<>();
    if (latchAndCallables.latch.await(milliseconds, TimeUnit.MILLISECONDS)) {
      for (CountdownedCallable<T> call : latchAndCallables.wrappedCallables) {
        rets.add(call.getResult());
      }
    } else {
      for (Future<T> future : futurres) {
        if (!future.isDone()) {
          future.cancel(true);
        }
      }
    }
    return rets;
  }

  public <T> List<T> waitAllCallables(List<Callable<T>> calls, int seconds) throws Exception {
    Preconditions.checkArgument(null != calls && !calls.isEmpty(), "callable empty.");
    LatchedCallables<T> latchAndCallables = wrapCallables(calls);
    for (CountdownedCallable<T> callable : latchAndCallables.wrappedCallables) {
      executorService.submit(callable);
    }
    List<T> rets = new ArrayList<>();
    if (latchAndCallables.latch.await(seconds, TimeUnit.SECONDS)) {
      for (CountdownedCallable<T> call : latchAndCallables.wrappedCallables) {
        rets.add(call.getResult());
      }
    }
    return rets;
  }

  public <T> List<T> waitAllCallables(@SuppressWarnings("unchecked") Callable<T>... calls) throws Exception {
    Preconditions.checkNotNull(calls, "callable empty.");
    return waitAllCallables(Arrays.asList(calls), DEFAULT_WAIT_SECONDS);
  }

  private static <T> LatchedCallables<T> wrapCallables(List<Callable<T>> callables) {
    CountDownLatch latch = new CountDownLatch(callables.size());
    List<CountdownedCallable<T>> wrapped = new ArrayList<>(callables.size());
    for (Callable<T> callable : callables) {
      wrapped.add(new CountdownedCallable<>(callable, latch));
    }

    LatchedCallables<T> returnVal = new LatchedCallables<>();
    returnVal.latch = latch;
    returnVal.wrappedCallables = wrapped;
    return returnVal;
  }

  public static class LatchedCallables<T> {
    public CountDownLatch latch;
    public List<CountdownedCallable<T>> wrappedCallables;
  }

  public static class CountdownedCallable<T> implements Callable<T> {
    private final Callable<T> wrapped;
    private final CountDownLatch latch;
    private T result;

    public CountdownedCallable(Callable<T> wrapped, CountDownLatch latch) {
      this.wrapped = wrapped;
      this.latch = latch;
    }

    @Override
    public T call() throws Exception {
      try {
        result = wrapped.call();
        return result;
      } finally {
        latch.countDown();
      }
    }

    public T getResult() {
      return result;
    }
  }

}

4、創(chuàng)建一個(gè)測(cè)試類

package com.hao;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.hao.bean.Employee;
import com.hao.service.EmployeeService;
import com.hao.service.ExecutorContext;

public class ExecutorTest extends BaseTest {

  @Autowired
  ExecutorContext executorContext;
  
  @Autowired
  EmployeeService employeeService;

  @Test
  public void test01() {
    long t0 = System.currentTimeMillis();
    List<Employee> employees = new ArrayList<Employee>();
    try {
      List<Callable<Integer>> calls = new ArrayList<Callable<Integer>>();
      Callable<Integer> able1 = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
          Thread.sleep(5000);
          Employee employee = employeeService.getById(1L);
          employees.add(employee);
          return 1;
        }

      };
      calls.add(able1);
      Callable<Integer> able2 = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
          Thread.sleep(5000);
          Employee employee = employeeService.getById(2L);
          employees.add(employee);
          return 2;
        }

      };
      calls.add(able2);
      Callable<Integer> able3 = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
          Thread.sleep(5000);
          Employee employee = employeeService.getById(3L);
          employees.add(employee);
          return 3;
        }

      };
      calls.add(able3);

      executorContext.waitAllCallables(calls, 5000);
    } catch (Exception e) {
      e.printStackTrace();
    }
    for (Employee employee : employees) {
      System.out.println(employee);
    }
    System.out.println(System.currentTimeMillis() - t0);
  }

}

5、執(zhí)行結(jié)果如下

次工具類的好處在于能夠像使用普通 service一樣使用線程池完成并行操作,當(dāng)然不要忘記將 ExecutorContext 置于能被sping掃描到的地方,

否則不能直接使用@Autowired 依賴注入

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 用Java實(shí)現(xiàn)24點(diǎn)游戲

    用Java實(shí)現(xiàn)24點(diǎn)游戲

    喜歡玩游戲的有福啦,文中有非常詳細(xì)的開發(fā)框架,按著框架來實(shí)現(xiàn)就好啦.而且24點(diǎn)游戲是經(jīng)典的紙牌益智游戲.,需要的朋友可以參考下
    2021-05-05
  • HashMap底層數(shù)據(jù)結(jié)構(gòu)詳細(xì)解析

    HashMap底層數(shù)據(jù)結(jié)構(gòu)詳細(xì)解析

    這篇文章主要介紹了HashMap底層數(shù)據(jù)結(jié)構(gòu)詳細(xì)解析,HashMap作為開發(fā)中常用的數(shù)據(jù)結(jié)構(gòu),也是面試中經(jīng)常被問的知識(shí)點(diǎn),因此作為開發(fā)者應(yīng)該盡可能多的理解其底層的數(shù)據(jù)結(jié)構(gòu),需要的朋友可以參考下
    2023-11-11
  • SpringMvc+POI處理excel表數(shù)據(jù)導(dǎo)入

    SpringMvc+POI處理excel表數(shù)據(jù)導(dǎo)入

    這篇文章主要為大家詳細(xì)介紹了SpringMvc+POI處理excel表數(shù)據(jù)導(dǎo)入,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • 詳解JavaEE使用過濾器實(shí)現(xiàn)登錄(用戶自動(dòng)登錄 安全登錄 取消自動(dòng)登錄黑用戶禁止登錄)

    詳解JavaEE使用過濾器實(shí)現(xiàn)登錄(用戶自動(dòng)登錄 安全登錄 取消自動(dòng)登錄黑用戶禁止登錄)

    主要介紹用戶的自動(dòng)登錄和取消自動(dòng)登錄,以及實(shí)現(xiàn)一天自動(dòng)登錄或者n天實(shí)現(xiàn)自動(dòng)登錄,當(dāng)用戶ip被加入到黑名單之后,直接利用過濾器返回一個(gè)警告頁(yè)面。接下來通過本文給大家介紹JavaEE使用過濾器實(shí)現(xiàn)登錄的相關(guān)知識(shí),感興趣的朋友一起學(xué)習(xí)吧
    2016-05-05
  • Mybatis關(guān)聯(lián)映射舉例詳解

    Mybatis關(guān)聯(lián)映射舉例詳解

    關(guān)聯(lián)關(guān)系是面向?qū)ο蠓治?、面向?qū)ο笤O(shè)計(jì)最終的思想,Mybatis完全可以理解這種關(guān)聯(lián)關(guān)系,如果關(guān)系得當(dāng),Mybatis的關(guān)聯(lián)映射將可以大大簡(jiǎn)化持久層數(shù)據(jù)的訪問
    2022-07-07
  • JAVA中Comparable接口和自定義比較器示例講解

    JAVA中Comparable接口和自定義比較器示例講解

    這篇文章主要給大家介紹了關(guān)于JAVA中Comparable接口和自定義比較器的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • SpringBoot實(shí)現(xiàn)聯(lián)表查詢的代碼詳解

    SpringBoot實(shí)現(xiàn)聯(lián)表查詢的代碼詳解

    這篇文章主要介紹了SpringBoot中如何實(shí)現(xiàn)聯(lián)表查詢,文中通過代碼示例和圖文結(jié)合的方式講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-05-05
  • Mybatis-Plus-AutoGenerator 最詳細(xì)使用方法

    Mybatis-Plus-AutoGenerator 最詳細(xì)使用方法

    這篇文章主要介紹了Mybatis-Plus-AutoGenerator 最詳細(xì)使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • 30分鐘入門Java8之lambda表達(dá)式學(xué)習(xí)

    30分鐘入門Java8之lambda表達(dá)式學(xué)習(xí)

    本篇文章主要介紹了30分鐘入門Java8之lambda表達(dá)式學(xué)習(xí),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-04-04
  • Java常見的轉(zhuǎn)義字符舉例詳解

    Java常見的轉(zhuǎn)義字符舉例詳解

    在java字符常量中,反斜杠(\)是一個(gè)特殊的字符,被稱為轉(zhuǎn)義字符,它的作用是用來轉(zhuǎn)義后面一個(gè)字符,這篇文章主要給大吉介紹了關(guān)于Java常見轉(zhuǎn)義字符的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-02-02

最新評(píng)論

保靖县| 修文县| 兴城市| 中牟县| 桃江县| 池州市| 股票| 淳化县| 马关县| 航空| 乌拉特前旗| 德阳市| 辽阳市| 柳江县| 平邑县| 清原| 安远县| 沧州市| 鸡西市| 山阳县| 万源市| 顺昌县| 石狮市| 澄迈县| 汽车| 莫力| 秭归县| 从江县| 塔城市| 平利县| 宜丰县| 区。| 云梦县| 萨嘎县| 志丹县| 凤山市| 广元市| 麻城市| 临海市| 卓尼县| 舟曲县|