初识线程池

2019-08-16 11:38:44来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

初识线程池

下面是几种常用的线程池,并初步了解其原理。
 1 public class TestThreadPool {
 2     public static void main(String[] args) {
 3         //1.单个线程
 4         //new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
 5         ExecutorService executor1 = Executors.newSingleThreadExecutor();
 6 
 7         //2.创建一个线程池,该线程池重用固定数量的从共享无界队列中运行的线程
 8         //int nThreads = 2;
 9         //new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
10         ExecutorService executor2 = Executors.newFixedThreadPool(2);
11 
12         //3.创建一个根据需要创建新线程的线程池,但在可用时将重新使用以前构造的线程
13         //new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
14         ExecutorService executor3 = Executors.newCachedThreadPool();
15 
16         //4.创建一个线程池,可以调度命令在给定的延迟之后运行,或定期执行
17         //new ScheduledThreadPoolExecutor(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());
18         //new ThreadPoolExecutor(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue(), threadFactory, handler)
19         ExecutorService executor4 = Executors.newScheduledThreadPool(2);
20 
21         BlockingQueue workQueue = null;
22         //new ThreadPoolExecutor(orePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler);
23         ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 20, 30, TimeUnit.SECONDS, workQueue);
24         executor.execute(new Runnable() {
25             @Override
26             public void run() {
27 
28             }
29         });
30     }
31 }
其中:
executor1,executor2,executor3 的最终都是调用 new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler),只是参数的值不同;
executor4 首先调用 new ScheduledThreadPoolExecutor(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()),
最终也是调用了new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler)。
 1 public ThreadPoolExecutor(int corePoolSize,
 2                           int maximumPoolSize,
 3                           long keepAliveTime,
 4                           TimeUnit unit,
 5                           BlockingQueue<Runnable> workQueue,
 6                           ThreadFactory threadFactory,
 7                           RejectedExecutionHandler handler) {
 8     if (corePoolSize < 0 ||
 9         maximumPoolSize <= 0 ||
10         maximumPoolSize < corePoolSize ||
11         keepAliveTime < 0)
12         throw new IllegalArgumentException();
13     if (workQueue == null || threadFactory == null || handler == null)
14         throw new NullPointerException();
15     this.acc = System.getSecurityManager() == null ?
16             null :
17             AccessController.getContext();
18     this.corePoolSize = corePoolSize;
19     this.maximumPoolSize = maximumPoolSize;
20     this.workQueue = workQueue;
21     this.keepAliveTime = unit.toNanos(keepAliveTime);
22     this.threadFactory = threadFactory;
23     this.handler = handler;
24 }
注:
//corePoolSize:核心线程数,线程池中允许的最小的线程数
//maximumPoolSize:线程池中最大的线程数
//keepAliveTime:当线程数大于核心线程数时,超过核心数的线程若等待了keepAliveTime时间还未有新任务将会被终止
//unit:keepAliveTime的单位
//workQueue:在任务执行之前用来保存多线程任务的队列
//threadFactory:创建新的线程的工厂
//handler:拒绝策略,由于线程数超出最大数量或是队列的最大容量时导致执行器阻塞时所执行的处理器,jdk8中handler的四种实现(默认采用AbortPolicy):
1.CallerRunsPolicy.rejectedExecution():由调用线程处理任务,当执行程序关闭的时候,任务也会被丢弃
public void rejectedExecution (Runnable r, ThreadPoolExecutor e){
    if (!e.isShutdown()) {
        r.run();
    }
}

2.AbortPolicy.rejectedExecution():直接抛出RejectedExecutionException异常
public void rejectedExecution (Runnable r, ThreadPoolExecutor e){
    throw new RejectedExecutionException("Task " + r.toString() +
            " rejected from " +
            e.toString());
}

3.DiscardPolicy.rejectedExecution():什么也不做,直接丢弃任务
public void rejectedExecution (Runnable r, ThreadPoolExecutor e){
}

4.DiscardOldestPolicy.rejectedExecution():执行器未关闭的情况下,丢弃最旧的任务
public void rejectedExecution (Runnable r, ThreadPoolExecutor e){
    if (!e.isShutdown()) {
        e.getQueue().poll();
        e.execute(r);
    }
}

 

 

 




原文链接:https://www.cnblogs.com/shanshiyan/p/11281647.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Spring通过注解注入外部配置文件

下一篇:Java基础之UDP协议和TCP协议简介及简单案例的实现