Threadpoolexecutor Definition
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 RunnableTasks submitted by ExecuteMethod.
-
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 WorkqueueOr ThreadfactoryAre null.
Example of threadpoolexecutor
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(3),
new ThreadPoolExecutor.DiscardOldestPolicy()
);
How to add a task to a thread pool
Step 1: Define a task
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);
}
}
Step 2: Add a task
Threadpool.exe cute (New mytask ("killing evils ~ "));
How is the thread in the thread pool dynamically adjusted?
(1) Under normal circumstances, a maximumcorePoolSizeThreads to execute the task;
(2) If the number of tasks increases,Corepoolsize cannot be done, you canCongestion in workqueue
(3) If the queue is full, try to start a new thread again (Maximumpoolsize-Corepoolsize)
(4) If the number of tasks continues to increase,Workqueue is full,AllMaximumpoolsize cannot be executed.
Here are some interesting explanations:
Http://wenku.baidu.com/view/8f4fc14ffe4733687e21aa55.html