Sun in the JAVA5, the Java thread of the class library to do a lot of expansion, in which the thread pool is one of the new features of JAVA5, in addition to the thread pool, there are many multi-threaded related content, for multi-threaded programming has brought great convenience. In order to write high-performance and stable and reliable multithreaded programs, the new content of the thread part is particularly important.
The contents of the JAVA5 line assigns feature are all under Java.util.concurrent, which contains a number of interfaces and classes, and familiarity with this part of the API feature is a difficult learning process. At present, there are few information and books on this aspect, most of the thread-related books still stay at the knowledge level before Java5.
Before Java5, to implement a thread pool is quite difficult, now Java5 for us to do everything, we just need to follow the provided API to use, can enjoy the great convenience of the thread pool.
The basic idea of the thread pool is also the idea of an object pool, which opens up a memory space in which many (not dead) threads are stored, and the thread execution schedule is handled by the pool manager. When a thread task is taken from a pool, the threads object is pooled after execution, which avoids the performance overhead of repeatedly creating thread objects and saves system resources.
JAVA5 provides 5 types of thread pools, such as the following:
One: newcachedthreadpool-variable-size thread pool (cache thread pool)
(1) Cache-type pool, first see if there are no previously established threads in the pool, if so, reuse (reuse), if not, create a new thread to join the pool;
(2) buffer pool, usually used to perform some short-lived asynchronous tasks , so some connection-oriented daemon-type server is not used much;
(3) can reuse (reuse) thread, must be timeout idle in the pool line, the default timeout is 60s, more than this idle time, the thread instance will be terminated and removed from the pool;
(4) Note that the thread that is put into the cachedthreadpool does not have to worry about its end, exceeding timeout inactivity, which is automatically terminated.
Two: newfixedthreadpool-fixed-size thread pool
(1) Newfixedthreadpool and Cachethreadpool are similar, but also can reuse use, but can not build new threads at any time;
(2) Its uniqueness: At any point in time, there can be at most a fixed number of active threads, at this time, if there are new threads to be established, can only be placed in another queue to wait until a thread in the current thread termination is directly removed from the pool;
(3) Unlike Cachethreadpool, Fixedthreadpool does not have an idle mechanism (possibly, but since the document is not mentioned, it must be very long, similar to the TCP or UDP idle mechanism that relies on the upper layer), so Fixedthreadpool most for some very stable and fixed regular concurrent threads, more for the server ;
(4) from the source code of the method, the cache pool and the fixed pool call the same underlying pool, except that the parameters are different:
Fixed pool thread count, and is 0 seconds idle (no idle);
The number of cache pool threads supports 0-integer.max_value (apparently completely without regard to the host's resource tolerance), 60 seconds idle.
Three: scheduledthreadpool-dispatch thread pool
(1) Scheduling type thread pool;
(2) The thread in this pool can be executed by schedule, or cycle execution.
Four: singlethreadexecutor-single-instance thread pool
(1) Single thread, can only have one thread in any time pool ;
(2) uses the same underlying pool as the cache pool and the fixed pool, but the number of threads is 1-1, and 0 seconds is idle (no idle).
Package Cn.thread;import java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * thread Pool usage * * @ Author Lin Yi-chin * @version 1.0 2013-7-25 a.m. 10:00:46 */public class Threadpooltest {public static void main (string[] args) { Threadpooltest test=new threadpooltest (); Create a thread pool that can reuse a fixed number of threads executorservice pool = Executors.newfixedthreadpool (2); The Runnable interface object is created, and the thread object of course implements the Runnable interface thread T1 = test.new MyThread (); Thread t2 = test.new MyThread (); Thread t3 = test.new MyThread (); Thread T4 = Test.new MyThread (); Thread T5 = Test.new MyThread (); Put the thread into the pool for execution pool.execute (T1); Pool.execute (T2); Pool.execute (T3); Pool.execute (T4); Pool.execute (T5); Close the thread pool Pool.shutdown (); } class MyThread extends thread {@Override public void run () {System.out.println (thread. CurrentThread (). GetName () + "executing. "); try {thread.sleep (100); } catch (Interruptedexception e) {e.printstacktrace (); } } }}
V. Custom thread pool
Threadpoolexecutor
Public threadpoolexecutor (int corepoolsize,
int Maximumpoolsize,
Long KeepAliveTime,
Timeunit Unit,
Blockingqueue<runnable> workQueue)
Parameters:
Corepoolsize
Core threads, the core thread will remain alive even if no tasks are required to be processed. When the number of threads is less than the number of core threads, even if an existing thread is idle, the thread pool prioritizes the creation of new threads to handle tasks rather than handing them over to existing threads.
The core thread exits when Allowcorethreadtimeout is set to true, and does not exit by default.
Maximumpoolsize
When the number of threads is greater than or equal to the core thread, and the task queue is full, the line pool creates a new thread until the number of threads reaches Maxpoolsize. If the number of threads is equal to Maxpoolsize, and the task queue is full, the processing power of the thread pool is exceeded, and the thread pool rejects processing the task and throws an exception.
KeepAliveTime
When the thread idle time reaches KeepAliveTime, the thread exits until the number of threads equals Corepoolsize. If Allowcorethreadtimeout is set to True, all threads exit until the number of threads is 0.
Unit
The time unit of the KeepAliveTime parameter.
WorkQueue
The queue used to hold the task before execution. This queue keeps only the Runnable tasks that are submitted by the Execute method.
Thrown:
IllegalArgumentException-If corepoolsize or KeepAliveTime is less than 0, or maximumpoolsize is less than or equal to zero, or corepoolsize Greater than maximumpoolsize.
NullPointerException-if workqueue is null
eg
Create a wait queue
blockingqueue<runnable> queue = new arrayblockingqueue<runnable> (20);
Creates a single-threaded execution program that can schedule a command to run after a given delay or perform it on a regular basis.
Threadpoolexecutor pool = new Threadpoolexecutor (2, 3, 2, timeunit.milliseconds, queue);
The Runnable interface object is created, and the thread object, of course, implements the Runnable interface.
Thread T1 = new MyThread ();
Thread t2 = new MyThread ();
Putting a thread into the pool for execution
Pool.execute (t1);
Pool.execute (T2);
Close the thread pool
Pool.shutdown ();
Package Cn.thread;import Java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.threadpoolexecutor;import java.util.concurrent.timeunit;/** * Custom Connection Pool * * @author 林计钦 * @version 1.0 2013-7-25 am 10:09:17 */public class Threadpoolexecutortest {public static void main (string[] args) {Threadpoo Ltest test = new Threadpooltest (); Create wait queue blockingqueue<runnable> Bqueue = new arrayblockingqueue<runnable> (20); Creates a single-threaded execution program that can schedule a command to run after a given delay or perform it on a regular basis. Threadpoolexecutor pool = new Threadpoolexecutor (2, 3, 2, Timeunit.milliseconds, bqueue); The Runnable interface object is created, and the thread object of course implements the Runnable interface thread T1 = test.new MyThread (); Thread t2 = test.new MyThread (); Thread t3 = test.new MyThread (); Thread T4 = Test.new MyThread (); Thread T5 = Test.new MyThread (); Thread T6 = Test.new MyThread (); Thread t7 = Test.new MyThread (); Putting a thread into the pool for execution Pool.execute (t1); Pool.execute (T2); Pool.execute (T3); Pool.execute (T4); Pool.execute (T5); Pool.execute (T6); Pool.execute (T7); Close the thread pool Pool.shutdown (); } class MyThread extends Thread {@Override public void run () {System.out.println (Thread.curr Entthread (). GetName () + "executing. "); try {thread.sleep (100); } catch (Interruptedexception e) {e.printstacktrace (); } } }}
Java multithreading-new features-thread pool