栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java ThreadPool线程池的使用,线程池工具类用法说明

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java ThreadPool线程池的使用,线程池工具类用法说明

实际上java已经提供线程池的实现 ExecutorService。

为了更方便的使用和管理。这里提供一个线程池工具类,方便大家的使用。

直接看看代码:

使用

public static void main(String[] args)
  {
    //实例化一个固定数目的线程池。具体参考类的构造方法
    ThreadPool threadPool=new ThreadPool(ThreadPool.FixedThread,5);
    //线程池执行线程
    threadPool.execute(new Runnable() {
      @Override
      public void run() {
 
      }
    });
  }

工具类:

package com.rbl.ncf.common.plugin.threadpool;
 
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
 

public class ThreadPool {
 
  public static final int FixedThread = 0;
 
  public static final int CachedThread = 1;
 
  public static final int SingleThread = 2;
 
  @Retention(RetentionPolicy.SOURCE)
  public @interface Type {
  }
 
  private ExecutorService exec;
 
  private ScheduledExecutorService scheduleExec;
 
  private ThreadPool() {
    throw new UnsupportedOperationException("u can't instantiate me...");
  }
 
  
  public ThreadPool(final int type, final int corePoolSize) {
    // 构造有定时功能的线程池
    // ThreadPoolExecutor(corePoolSize, Integer.MAX_VALUE, 10L, TimeUnit.MILLISECONDS, new
    // BlockingQueue)
    scheduleExec = Executors.newScheduledThreadPool(corePoolSize);
    switch (type) {
      case FixedThread:
 // 构造一个固定线程数目的线程池
 // ThreadPoolExecutor(corePoolSize, corePoolSize, 0L, TimeUnit.MILLISECONDS, new
 // linkedBlockingQueue());
 exec = Executors.newFixedThreadPool(corePoolSize);
 break;
      case SingleThread:
 // 构造一个只支持一个线程的线程池,相当于newFixedThreadPool(1)
 // ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new
 // linkedBlockingQueue())
 exec = Executors.newSingleThreadExecutor();
 break;
      case CachedThread:
 // 构造一个缓冲功能的线程池
 // ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new
 // SynchronousQueue());
 exec = Executors.newCachedThreadPool();
 break;
    }
  }
 
  
  public void execute(final Runnable command) {
    exec.execute(command);
  }
 
  
  public void execute(final List commands) {
    for (Runnable command : commands) {
      exec.execute(command);
    }
  }
 
  
  public void shutDown() {
    exec.shutdown();
  }
 
  
  public List shutDownNow() {
    return exec.shutdownNow();
  }
 
  
  public boolean isShutDown() {
    return exec.isShutdown();
  }
 
  
  public boolean isTerminated() {
    return exec.isTerminated();
  }
 
  
  public boolean awaitTermination(final long timeout, final TimeUnit unit)
      throws InterruptedException {
    return exec.awaitTermination(timeout, unit);
  }
 
  
  public  Future submit(final Callable task) {
    return exec.submit(task);
  }
 
  
  public  Future submit(final Runnable task, final T result) {
    return exec.submit(task, result);
  }
 
  
  public Future submit(final Runnable task) {
    return exec.submit(task);
  }
 
  
  public  List> invokeAll(final Collection> tasks)
      throws InterruptedException {
    return exec.invokeAll(tasks);
  }
 
  
  public  List> invokeAll(final Collection> tasks,
final long timeout, final TimeUnit unit)
      throws InterruptedException {
    return exec.invokeAll(tasks, timeout, unit);
  }
 
  
  public  T invokeAny(final Collection> tasks)
      throws InterruptedException, ExecutionException {
    return exec.invokeAny(tasks);
  }
 
  
  public  T invokeAny(final Collection> tasks, final long timeout,
final TimeUnit unit)
      throws InterruptedException, ExecutionException, TimeoutException {
    return exec.invokeAny(tasks, timeout, unit);
  }
 
  
  public ScheduledFuture schedule(final Runnable command, final long delay,
      final TimeUnit unit) {
    return scheduleExec.schedule(command, delay, unit);
  }
 
  
  public  ScheduledFuture schedule(final Callable callable, final long delay,
 final TimeUnit unit) {
    return scheduleExec.schedule(callable, delay, unit);
  }
 
  
  public ScheduledFuture scheduleWithFixedRate(final Runnable command,
     final long initialDelay, final long period,
     final TimeUnit unit) {
    return scheduleExec.scheduleAtFixedRate(command, initialDelay, period, unit);
  }
 
  
  public ScheduledFuture scheduleWithFixedDelay(final Runnable command,
      final long initialDelay, final long delay,
      final TimeUnit unit) {
    return scheduleExec.scheduleWithFixedDelay(command, initialDelay, delay, unit);
  } 
}

补充知识:Java线程池之ThreadPoolExecutor以及工具类Executors类

首先,介绍线程池的概念。

简单讲,就是有一个“池”内放着一些已经启动的线程,这些线程一直启动,用来执行线程池接受的任务。这些线程我们称为核心线程。

当接收任务过多时,会进入阻塞队列进行存储。

而如果阻塞队列也满,则会创建线程来执行任务,这些任务称为救急线程。救急线程任务结束后会根据存活时间来释放

ThreadPoolExecutor的创建参数就是基于上述的概念:

ThreadPoolExecutor(int corePoolSize,//核心线程数目
   int maximumPoolSize,//最大线程数 = 核心线程数 + 救急线程数
   long keepAliveTime,//救急线程的存活超时时间
   TimeUnit unit,//超时时间的单位
   BlockingQueue workQueue,//阻塞队列
   ThreadFactory threadFactory,//线程工厂,主要用于给线程起名,
   RejectedExecutionHandler handler)//拒绝策略,即队列满了后再接受任务怎么处理

会有多种构造方法,常用的是前5个参数的构造。本质上都是调用了这个构造方法

ThreadPoolExecutor类继承自AbstractExecutorService类,而AbstractExecutorService类实现了ExecutorService接口。(因为后面工具类的返回值是ExecutorService接口对象,而不是ThreadPoolExecutor对象)。线程池操作都定义在ExecutorService接口中。

根据不同的需求,会产生不同的线程池。为了方便,有了Executors类来创建一些常用的线程池,注意的是返回值是ExecutorService对象

需求一:固定大小的线程池,即Executors.newFixedThreadPool(corePoolSize)。是只有一定数量的核心数量(参数),即核心数目等于总数目。阻塞队列使用的是linkedBlockingQueue。适应于任务数量已知,且相对耗时

本质是调用了

ThreadPoolExecutor(corePoolSize,coreSize,0,TimeUnit.MILLISECONDS,new linkedBlockingQueue() )

需求二、带缓冲区的线程队列,即Executors.newCachedThreadPool()。没有核心线程,全都是救急线程。超时时间设为60秒。阻塞队列使用的是SynchronousQueue。 该队列没有容量,没有线程取任务是不能够放任务的。

本质调用:

ThreadPoolExecutor(0,Integer.MAx_VALUE,60L,TimeUnit.SECONDS,new SynchronousQueue() )

需求三:单线程线程池:即Executors.newSingleThreadPool() , 即需求一的特殊情况,只有一个核心线程。即:

ThreadPoolExecutor(1,1,0,TimeUnit.MILLISECONDS,new linkedBlockingQueue() )

以上这篇java ThreadPool线程池的使用,线程池工具类用法说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/131207.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号