Java并发性ThreadPoolExecutor类


java.util.concurrent.ThreadPoolExecutor是一个ExecutorService,用于执行每个提交的任务,使用可能的几个池线程之一,通常使用Executors工厂方法进行配置。它还提供各种实用方法来检查当前的线程统计信息并对其进行控制。

ThreadPoolExecutor方法

Sr.No. 方法和描述
1 afterExecute(Runnable r,Throwable t) 在完成给定Runnable的执行后调用的方法。
2 void allowCoreThreadTimeOut(boolean value) 设置策略来管理核心线程是否可能超时并在保持活动时间内没有任何任务到达时终止,当新任务到达时如果需要则替换。
3 boolean allowsCoreThreadTimeOut() 如果此池允许核心线程超时并在keepAlive时间内没有任何任务到达时终止,则返回true;如果新任务到达时需要替换,则返回true。
4 boolean awaitTermination(long timeout, TimeUnit unit) 阻塞,直到所有任务在关闭请求之后所有任务都已完成执行,或发生超时,或当前线程中断,以先发生者为准。
5 protected void beforeExecute(Thread t, Runnable r) 在给定线程中执行给定Runnable之前调用的方法。
6 void execute(Runnable command) 将来执行给定的任务。
7 protected void finalize() 当这个执行器不再被引用并且它没有线程时调用shutdown。
8 int getActiveCount() 返回正在执行任务的线程的近似数量。
9 long getCompletedTaskCount() 返回已完成执行的大约总任务数。
10 int getCorePoolSize() 返回线程的核心数量。
11 long getKeepAliveTime(TimeUnit unit) 返回线程保持活动时间,线程保持活动时间是超过核心池大小的线程在终止之前可能保持空闲的时间量。
12 int getLargestPoolSize() 返回池中同时存在的最大线程数。
13 int getMaximumPoolSize() 返回允许的最大线程数。
14 int getPoolSize() 返回池中的当前线程数。
15 BlockingQueue getQueue() 返回此执行程序使用的任务队列。
15 RejectedExecutionHandler getRejectedExecutionHandler() 返回不可执行任务的当前处理程序。
16 long getTaskCount() 返回曾经计划执行的任务的近似总数。
17 ThreadFactory getThreadFactory() 返回用于创建新线程的线程工厂。
18 boolean isShutdown() 如果此执行程序已关闭,则返回true。
19 boolean isTerminated() 如果所有任务在关闭后都完成,则返回true。
20 boolean isTerminating() 如果此执行程序正在shutdown()或shutdownNow()之后终止,但尚未完全终止,则返回true。
21 int prestartAllCoreThreads() 启动所有核心线程,导致它们空闲地等待工作。
22 boolean prestartCoreThread() 启动一个核心线程,导致它闲置地等待工作。
23 void purge() 尝试从工作队列中删除所有已取消的未来任务。
24 boolean remove(Runnable task) 如果该任务存在,则从执行程序的内部队列中删除此任务,从而导致它在尚未启动的情况下不会运行。
25 void setCorePoolSize(int corePoolSize) 设置线程的核心数量。
26 void setKeepAliveTime(long time,TimeUnit unit) 设置线程在终止之前可能保持空闲的时间限制。
27 void setMaximumPoolSize(int maximumPoolSize) 设置允许的最大线程数。
28 void setRejectedExecutionHandler(RejectedExecutionHandler handler) 为不可执行的任务设置新的处理程序。
29 void setThreadFactory(ThreadFactory threadFactory) 设置用于创建新线程的线程工厂。
30 void shutdown() 启动先前提交的任务执行的有序关闭,但不会接受新任务。
31 List shutdownNow() 尝试停止所有正在执行的任务,暂停等待任务的处理,并返回正在等待执行的任务列表。
32 protected void terminated() Executor终止时调用的方法。
33 String toString() 返回标识此池的字符串及其状态,包括运行状态的指示以及估计的工人和任务计数。

以下TestThread程序显示基于线程的环境中ThreadPoolExecutor接口的用法。

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newCachedThreadPool();

      //Stats before tasks execution
      System.out.println("Largest executions: "
         + executor.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + executor.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + executor.getPoolSize());
      System.out.println("Currently executing threads: "
         + executor.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + executor.getTaskCount());

      executor.submit(new Task());
      executor.submit(new Task());

      //Stats after tasks execution
      System.out.println("Core threads: " + executor.getCorePoolSize());
      System.out.println("Largest executions: "
         + executor.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + executor.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + executor.getPoolSize());
      System.out.println("Currently executing threads: "
         + executor.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + executor.getTaskCount());

      executor.shutdown();
   }  

   static class Task implements Runnable {

      public void run() {

         try {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Running Task! Thread Name: " +
               Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Task Completed! Thread Name: " +
               Thread.currentThread().getName());
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

这将产生以下结果。

输出

Largest executions: 0
Maximum allowed threads: 2147483647
Current threads in pool: 0
Currently executing threads: 0
Total number of threads(ever scheduled): 0
Core threads: 0
Largest executions: 2
Maximum allowed threads: 2147483647
Current threads in pool: 2
Currently executing threads: 2
Total number of threads(ever scheduled): 2
Running Task! Thread Name: pool-1-thread-2
Running Task! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-2