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