With the contribution of Doug Lea, A multithreading master, many concurrent features are added to JDK1.5, such as the thread pool. Here we will introduce the simple usage of 1.5 thread pools.
Created on:
Last modification date:
Panhaidong@gmail.com
I. Introduction
The thread pool class is java. util. concurrent. ThreadPoolExecutor. The common constructor is as follows:
Threadpoolexecutor (INT corepoolsize, <br/> int maximumpoolsize, <br/> long KeepAliveTime, timeunit unit, <br/> blockingqueue <runnable> workqueue, <br/> worker handler)
- Corepoolsize
Minimum number of threads maintained by the thread pool
- Maximumpoolsiz
Maximum number of threads maintained by the thread pool
- KeepAliveTime
The idle time allowed by the thread pool to maintain the thread
- Unit
Unit of idle time allowed by the thread pool maintenance thread
- Workqueue
Buffer Queue used by the thread pool
- Handler
Policy of the thread pool to reject tasks
A task is added to the thread pool using the execute (Runnable) method. A task is a Runnable object. The execution method of a task is the run () method of a Runnable object.
When a task is added to the thread pool through the execute (Runnable) method:
- If the number of threads in the thread pool is smaller than corepoolsize, a new thread should be created to process the added tasks even if all threads in the thread pool are idle.
- If the number in the thread pool is equal to corepoolsize, but the Buffer Queue workqueue is not full, the task is put into the buffer queue.
- If the number in the thread pool is greater than corepoolsize, the Buffer Queue workqueue is full, and the number in the thread pool is smaller than maximumpoolsize, a new thread is created to process the added task.
- If the number in the thread pool is greater than corepoolsize, the Buffer Queue workqueue is full, and the number in the thread pool is equal to maximumpoolsize, the handler policy is used to process the task.
That is, the priority of the processing task is:
Core Thread corePoolSize, task queue workQueue, and maximumPoolSize. If all three are full, handler is used to process the rejected task.
When the number of threads in the thread pool is greater than corePoolSize, if the idle time of a thread exceeds keepAliveTime, the thread will be terminated. In this way, the thread pool can dynamically adjust the number of threads in the pool.
The optional parameters of unit are several static attributes in java. util. concurrent. TimeUnit:
NANOSECONDS, MICROSECONDS, MILLISECONDS, and SECONDS.
WorkQueue I often use: java. util. concurrent. ArrayBlockingQueue
Handler has four options:
II. General Usage example [Download source code
]
Package cn.simplelife.exe rcise; <br/> import java. util. concurrent. arrayBlockingQueue; <br/> import java. util. concurrent. threadPoolExecutor; <br/> import java. util. concurrent. timeUnit; <br/> public class TestThreadPool {<br/> private static int produceTaskSleepTime = 2; <br/> public static void main (String [] args) {<br/> // construct a thread pool <br/> ThreadPoolExecutor producerPool = new ThreadPoolExecutor (2, 4, 0, TimeUnit. SECONDS, new ArrayBlockingQueue (3), new ThreadPoolExecutor. DiscardOldestPolicy (); <br/> // send a task to the thread pool at intervals of produceTaskSleepTime. <Br/> int I = 1; <br/> while (true) {<br/> try {<br/> Thread. sleep (produceTaskSleepTime); <br/> String task = "task @" + I; <br/> System. out. println ("put" + task); <br/> producerPool.exe cute (new ThreadPoolTask (task); <br/> I ++; <br/>} catch (Exception e) {<br/> e. printStackTrace (); <br/>}< br/>}
Package cn.simplelife.exe rcise; <br/> Import Java. io. serializable; <br/>/** <br/> * tasks executed by the thread pool <br/> * @ author hdpan <br/> */<br/> public class threadpooltask implements runnable, serializable {<br/> // In jdk1.5, it is recommended that such an id be declared for each class implementing the serializable interface <br/> Private Static final long serialversionuid = 0; <br/> Private Static int consumetasksleeptime = 2000; <br/> private object threadpooltaskdata; <br/> threadpooltask (Object tasks) {<br/> This. threadpooltaskdata = tasks; <br/>}< br/> // the execution process of each task. Nothing is done now, except print and sleep, :) <br/> Public void run () {<br/> system. out. println ("start .. "+ threadpooltaskdata); <br/> try {<br/> // easy to observe and wait for a while <br/> thread. sleep (consumetasksleeptime); <br/>} catch (exception e) {<br/> E. printstacktrace (); <br/>}< br/> threadpooltaskdata = NULL; <br/>}< br/>}
Description of the two procedures:
- In this program, a task is a runnable object, that is, a threadpooltask object.
- Generally, in addition to the processing method, the data to be processed is transmitted to the task through the constructor.
- In this program, the main () method is equivalent to a cruel leader who sends out many tasks and throws them to a group named threadpool.
- There are at least two members in this group. If the two are too busy, the task will be put into the task list.
- If there are too many tasks in the backlog and no more than three tasks can be installed in the task list, hire new players to help. However, for cost-based consideration, you cannot hire too many players. You can only hire up to four players.
- If the four players are busy and there are new tasks, the team will not be able to handle them, and the tasks will be handled through a strategy. Our approach is to keep distributing the tasks, until you accept this task (more cruel! Haha ).
- Because it is costly for a team member to work. If the team member is idle and no new tasks are available for the 3SECONDS instance, some Members will be dismissed. However, for the normal operation of the group, even if you are idle, the team members cannot be less than two.
- By adjusting the size of producetasksleeptime and consumetasksleeptime, we can control the speed of dispatching and processing tasks. By changing these two values, we can observe the program working conditions at different rates.
- By adjusting the data in Step 4, adding and adjusting the task discard policy, and replacing the other three policies, we can see different processing methods under different policies.
- For other usage methods, see the help of JDK, which is easy to understand and use.
Blog Source: http://dalezhu.javaeye.com/blog/186895