zoukankan      html  css  js  c++  java
  • Java,线程池,ThreadPoolExecutor

     飞机 ThreadPoolExecutor定义

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory)
    Creates a new ThreadPoolExecutorwith the given initial parameters and default rejected execution handler.
    Parameters:
    corePoolSize - the number of threads to keep in the pool, even if they are idle.
    maximumPoolSize - the maximum number of threads to allow in the pool.
    keepAliveTime - when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
    unit - the time unit for the keepAliveTime argument.
    workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
    threadFactory - the factory to use when the executor creates a new thread.
    Throws:
    IllegalArgumentException - if corePoolSize or keepAliveTime less than zero, or if maximumPoolSize less than or equal to zero, or if corePoolSize greater than maximumPoolSize.
    NullPointerException - if workQueue or threadFactory are null.

    飞机  ThreadPoolExecutor举例

    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS, 
                    new ArrayBlockingQueue<Runnable>(3), 
                    new ThreadPoolExecutor.DiscardOldestPolicy()
            );

    飞机  如何给线程池添加任务

    第一步:定义任务

    public class MyTask implements Runnable{
     
        private String name = null;
        public MyTask(final String name){
            this.name = name;
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            System.out.println("My task is " + this.name);
        }
     
    }

    第二步:添加任务

    threadPool.execute(new MyTask("killing evils~"));

    飞机  线程池中的线程,是如何动态调整的

    (1) 正常情况下,最多去维护corePoolSize 个线程来执行任务;

    (2) 如果任务不断增多,corePoolSize做不过来了,可以向workQueue里塞

    (3) 如果队列塞满了,那么再尝试启新线程来做,最多会再启(maximumPoolSize-corePoolSize)个

    (4) 如果任务还在不断增多,workQueue也满了,所有maximumPoolSize都执行不过来了,那么开始执行放弃策略。

    这里有比较有意思的讲解:

    http://wenku.baidu.com/view/8f4fc14ffe4733687e21aa55.html

     

  • 相关阅读:
    asp.net mvc4 之Webapi之应用客户端访问服务器端
    c#设计模式-----单例模式
    ASP.NET MVC4中ViewBag、ViewData和TempData的使用和区别
    c# winform窗体间的传值
    Extjs-树 Ext.tree.TreePanel 动态加载数据
    Entity Framework(EF)(一)之database first
    MD5加密算法
    Extjs form 表单的 submit
    XML 解析错误:找不到根元素
    C语言断言
  • 原文地址:https://www.cnblogs.com/alipayhutu/p/2520027.html
Copyright © 2011-2022 走看看