ThreadPoolExecutor线程池相关方法

ThreadPoolExecutor的构造函数说明:


public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue)
用给定的初始参数和默认的线程工厂及处理程序创建新的 ThreadPoolExecutor。使用 Executors 工厂方法之一比使用此通用构造方法方便得多。
参数:


corePoolSize - 池中所保存的线程数,包括空闲线程。指定ThreadPoolExecutor中持有的核心线程数, 除非task队列已满, ThreadPoolExecutor不会创建超过核心线程数的线程(corePoolSize为0时是一种特殊情况, 此时就算task队列没有饱和, 向线程池第一次提交task时仍然会创建新的线程), 核心线程一旦创建就不会销毁, 除非设置了allowCoreThreadTimeOut(true), 或者关闭线程池

maximumPoolSize - 池中允许的最大线程数。 对于超过核心线程数的线程, 如果在指定的超时时间内没有使用到, 就会被销毁
keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间:超时时间
unit - keepAliveTime 参数的时间单位。
workQueue - 执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 


抛出:
IllegalArgumentException - 如果 corePoolSize 或 keepAliveTime 小于零,或者 maximumPoolSize 小于或等于零,或者 corePoolSize 大于 maximumPoolSize。NullPointerException - 如果 workQueue 为 null

Executors类的静态方法创建线程池的源码:

public static ExecutorService newCachedThreadPool() {   // 核心线程数为0, 最大线程数为Integer.MAX_VALUE, 超时时间为60s   return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());  }    public static ExecutorService newFixedThreadPool(int nThreads) {   // 核心线程数和最大线程数都为调用方指定的值nThreads, 超时时间为0   return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,     new LinkedBlockingQueue<Runnable>());  }    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {   // 核心线程数由调用方指定, 最大线程数为Integer.MAX_VALUE, 超时时间为0   return new ThreadPoolExecutor(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue());  } 

    public static ExecutorService newSingleThreadExecutor() {

          / 核心线程数为1, 最大线程数为1, 超时时间为0
            return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

task队列(任务队列)

线程池内部持有一个task队列, 当task的提交速度超过task的执行速度时, task将被缓存在task队列中等待有线程可用时再执行. ThreadPoolExecutor在创建时可以为其指定task队列, 开发者一般有三种选择: 有界队列, 无界队列以及同步队列. Executors.newFixedThreadPool和Executors.newScheduledThreadPool返回的ThreadPoolExecutor对象使用的是无界队列, 而Executors.newCashedThreadPool返回的ThreadPoolExecutor对象使用的是同步队列.

线程数不多的线程池指定一个容量大的队列(或者无界队列), 有助于减少线程间切换, CPU等方面的消耗, 代价是可能会造成吞吐量下降. 如果使用的是有界队列, 队列可能会被填满, 此时将根据指定的饱和策略进行处理(见之后的讲述).

对于线程数很大的线程池, 可以使用同步队列. 同步队列(SynchronousQueue)其实不能算是一种队列, 因为同步队列没有缓存的作用. 使用同步队列时, task被提交时, 直接由线程池中的线程接手. 如果此时线程池中没有可用的线程, 线程池将创建新的线程接手. 如果线程池无法创建新的线程(比如线程数已到达maximumPoolSize), 则根据指定的饱和策略进行处理(同样见之后的讲述).

 

饱和策略

如果线程池使用的是有界队列, 那么当有界队列满时继续提交task时饱和策略会被触发.

如果线程池使用的是同步队列, 那么当线程池无法创建新的线程接手task时饱和策略会被触发.

如果线程池被关闭后, 仍然向其提交task时, 饱和策略也会被触发.

ThreadPoolExecutor.setRejectedExecutionHandler方法用于设定饱和策略. 该方法接受一个RejectedExecutionHandler对象作为参数. RejectedExecutionHandler只定义了一个方法:rejectedExecution(Runnable r, ThreadPoolExecutor executor). rejectedExecution方法在饱和策略被触发时由系统回调.

ThreadPoolExecutor类中预定义了多个RejectedExecutionHandler的实现类: AbortPolicy, CallerRunsPolicy, DiscardPolicy, 和DiscardOldestPolicy.

AbortPolicy是默认的饱和策略, 其rejectedExecution方法为:

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {   throw new RejectedExecutionException();  } 

可见默认情况下, 触发饱和策略时将抛出RejectedExecutionException异常.

CallerRunsPolicy. 饱和时将在提交task的线程中执行task, 而不是由线程池中的线程执行:

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {   if (!e.isShutdown()) {    r.run();   }  }

使用CallerRunsPolicy的例子:

class LifecycleWebServer {   // MAX_THREAD_COUNT和MAX_QUEUE_COUNT的值根据系统的实际情况确定   private static final int MAX_THREAD_COUNT = 100;   private static final int MAX_QUEUE_COUNT = 1000;     // 使用有界队列作为task队列, 当有界队列满时, 将触发饱和策略   private final ThreadPoolExecutor exec = new ThreadPoolExecutor(0, MAX_THREAD_COUNT, 60L, TimeUnit.SECONDS,     new ArrayBlockingQueue<Runnable>(MAX_QUEUE_COUNT));     public void start() throws IOException {    // 设置饱和策略为CallerRunsPolicy    exec.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());    ServerSocket socket = new ServerSocket(80);    while (!exec.isShutdown()) {     try {      final Socket conn = socket.accept();      exec.execute(new Runnable() {       public void run() {        handleRequest(conn);       }      });     } catch (RejectedExecutionException e) {      if (!exec.isShutdown())       log("task submission rejected", e);     }    }   }     public void stop() {    exec.shutdown();   }     void handleRequest(Socket connection) {    Request req = readRequest(connection);    if (isShutdownRequest(req))     stop();    else     dispatchRequest(req);   }      public static void main(String[] args) {    LifecycleWebServer server = new LifecycleWebServer();    try {     // 在main线程中启动server     server.start();    } catch (IOException e) {     e.printStackTrace();    }   }  } 

LifecycleWebServer中的线程池使用CallerRunsPolicy作为其饱和策略. 如果线程池饱和时main线程仍然向线程池提交task, 那么task将在main中执行. main线程执行task是需要一定时间的, 这样就给了线程池喘息的机会, 而且main线程在执行task的时间内无法接受socket连接, 因此socket连接请求将缓存在tcp层. 如果server过载持续的时间较长, 使得tcp层的缓存不够, 那么tcp缓存将根据其策略丢弃部分请求. 如此一来, 整个系统的过载压力逐步向外扩散: 线程池-线程池中的队列-main线程-tcp层-client. 这样的系统在发生过载时是比较优雅的: 既不会因为过多的请求而导致系统资源耗尽, 也不会一发生过载时就拒绝服务, 只有发生长时间系统过载时才会出现客户端无法连接的情况.

DiscardPolicy. 该策略将最新提交的task丢弃:

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {   // 丢弃, 不做任何处理  } 

DiscardOldestPolicy. 该策略丢弃队列中处于对头的task, 且试着再次提交最新的task:

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {      if (!e.isShutdown()) {   e.getQueue().poll();   e.execute(r);      }  } 

DiscardOldestPolicy与PriorityBlockingQueue结合使用时可能会造成不好的结果, 因为PriorityBlockingQueue中位于对头的task是优先级最高的task, 发生饱和时反而首先丢弃优先级高的task可能不符合需求.

ThreadPoolExecutor没有提供饱和时阻塞的策略, 不过开发者可以结合Semaphore实现:

public class BoundedExecutor {   private final Executor exec;   private final Semaphore semaphore;     public BoundedExecutor(Executor exec, int bound) {    this.exec = exec;    // 设定信号量permit的上限    this.semaphore = new Semaphore(bound);   }     public void submitTask(final Runnable command) throws InterruptedException {    // 提交task前先申请permit, 如果无法申请到permit, 调用submitTask的线程将被阻塞, 直到有permit可用    semaphore.acquire();    try {     exec.execute(new Runnable() {      public void run() {       try {        command.run();       } finally {        // 提交成功了, 运行task后释放permit        semaphore.release();       }      }     });    } catch (RejectedExecutionException e) {     // 如果没有提交成功, 也需要释放permit     semaphore.release();    }   }  }

 

ThreadFactory

在创建ThreadPoolExecutor时还可以为其指定ThreadFactory, 当线程池需要创建新的线程时会调用ThreadFactory的newThread方法. 默认的ThreadFactory创建的线程是nonDaemon, 线程优先级为NORM_PRIORITY的线程, 并且为其指定了可识别的线程名称:

public Thread newThread(Runnable r) {   Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);   if (t.isDaemon())    t.setDaemon(false);   if (t.getPriority() != Thread.NORM_PRIORITY)    t.setPriority(Thread.NORM_PRIORITY);   return t;  } 

开发者可以根据自身需要为ThreadPoolExecutor指定自定义的ThreadFactory. 例如:

public class MyThreadFactory implements ThreadFactory {   private final String poolName;     public MyThreadFactory(String poolName) {    this.poolName = poolName;   }     public Thread newThread(Runnable runnable) {    return new MyAppThread(runnable, poolName);   }  }    public class MyAppThread extends Thread {   public static final String DEFAULT_NAME = "MyAppThread";   private static volatile boolean debugLifecycle = false;   private static final AtomicInteger created = new AtomicInteger();   private static final AtomicInteger alive = new AtomicInteger();   private static final Logger log = Logger.getAnonymousLogger();     public MyAppThread(Runnable r) {    this(r, DEFAULT_NAME);   }     public MyAppThread(Runnable runnable, String name) {    // 为自定义的Thread类指定线程名称    super(runnable, name + "-" + created.incrementAndGet());    // 设置UncaughtExceptionHandler. UncaughtExceptionHandler的uncaughtException方法将在线程运行中抛出未捕获异常时由系统调用    setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {     public void uncaughtException(Thread t, Throwable e) {      log.log(Level.SEVERE, "UNCAUGHT in thread " + t.getName(), e);     }    });   }     public void run() {    // Copy debug flag to ensure consistent value throughout.     boolean debug = debugLifecycle;    if (debug)     log.log(Level.FINE, "Created " + getName());    try {     alive.incrementAndGet();     super.run();    } finally {     alive.decrementAndGet();     if (debug)      log.log(Level.FINE, "Exiting " + getName());    }   }     public static int getThreadsCreated() {    return created.get();   }     public static int getThreadsAlive() {    return alive.get();   }     public static boolean getDebug() {    return debugLifecycle;   }     public static void setDebug(boolean b) {    debugLifecycle = b;   }  }

 

扩展ThreadPoolExecutor

ThreadPoolExecutor类提供了多个"钩子"方法, 以供其子类实现, 比如beforeExecute, afterExecute, terminated等. 所谓"钩子"是指基类预留的, 但是没有提供具体实现的方法, 其方法体为空. 子类可以根据需要为"钩子"提供具体实现.

beforeExecute和afterExecute方法分别在执行task前后调用:

private void runTask(Runnable task) {   final ReentrantLock runLock = this.runLock;   runLock.lock();   try {    if (runState < STOP && Thread.interrupted() && runState >= STOP)     thread.interrupt();    boolean ran = false;    beforeExecute(thread, task);    try {     task.run();     ran = true;     afterExecute(task, null);     ++completedTasks;    } catch (RuntimeException ex) {     if (!ran)      afterExecute(task, ex);     throw ex;    }   } finally {    runLock.unlock();   }  } 

beforeExecute和afterExecute方法可以用于记录日志, 统计数据等操作.

terminated方法在线程池被关闭后调用. terminated方法可以用于释放线程池申请的资源.


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值