Java multithreading-new features-thread pool

Source: Internet
Author: User

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) cache pools, typically used to perform asynchronous tasks with short life cycles ; Therefore, some connection-oriented daemon-type server is not used much;  
(3) a thread that can reuse (re-use) must be the middle of a pool in timeout idle, and the default timeout is 60s, which exceeds this idle length, The thread instance will be terminated and removed from the pool;  
(4) Note that the thread that is put into 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 almost, but also can reuse use, but not at any time to build new threads;  
(2) Its uniqueness: At any point in time, there can be at most a fixed number of active threads, At this point, if a new thread is to be established, it can only wait in another queue until a thread in the current thread terminates directly from the pool;  
(3) differs from Cachethreadpool, Fixedthreadpool has no idle mechanism (possibly also, But since the document does not mention, it must be very long, similar to rely on the upper layer of TCP or UDP idle mechanism, and so on, so fixedthreadpool 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 0 seconds idle (no idle);
Number of cache pool threads support 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  Morning 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);          //creation implements the Runnable interface object, and the thread object certainly implements the Runnable interface           thread t1 = test.new mythread ();          thread t2 =&nbsP;test.new mythread ();         thread t3 =  Test.new mythread ();         thread t4 =  Test.new mythread ();         thread t5 =  Test.new mythread ();          //the thread into the pool for execution           pool.execute (t1);          Pool.execute (T2);          pool.execute (T3);          pool.execute (T4);          Pool.execute (T5);          //Close thread pool           pool.shutdown ();     }         class mythread extends thread {         @Override          public void run ()  {             system.out.println (Thread.CurrentThread (). GetName ()  +  "executing. ");            try {                 thread.sleep (;   )          } catch  (interruptedexception e)  {                  E.printstacktrace ();            }         }    }}

Five, custom thread pool
Threadpoolexecutor
Public Threadpoolexecutor (int corepoolsize,
int maximumpoolsize,
long KeepAliveTime,
Timeunit unit,
blockingqueue<runnable> workQueue)
parameter:
corepoolsize 
Core threads, the core thread will remain alive even if no tasks need to be handled. 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.

throw:
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 wait queue  
blockingqueue<runnable> queue = new Arrayblockingqueue<runnable> (; )
//Create a single-threaded execution program that can schedule commands to run after a given delay or perform them on a regular basis.  
Threadpoolexecutor pool = new Threadpoolexecutor (2, 3, 2, timeunit.milliseconds, queue);  
// The Runnable interface object is created, and the thread object also implements the Runnable interface  
Thread T1 = new MyThread ();  
Thread t2 = new MyThread (); nbsp
//The thread is put into the pool for execution  
Pool.execute (t1);  
Pool.execute (T2);  
//close 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 Pooling  *  *  @author   Lin Yi-chin  * @ version 1.0 2013-7-25  Morning 10:09:17 */public class threadpoolexecutortest {     public static void main (String[] args)  {         threadpooltest test = new threadpooltest ();         //  Create a wait queue          Blockingqueue<runnable> bqueue = new arrayblockingqueue<runnable> (; )        //  creates a single-threaded execution program that can schedule commands to run after a given delay or perform them on a regular basis.         threadpoolexecutor pool = new  Threadpoolexecutor (2, 3, 2, timeunit.milliseconds, bqueue);         //  creation implements the Runnable interface object, and the thread object certainly 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 ();        //  the 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 thread pool         pool.shutdown ();     }    class MyThread extends Thread {          @Override         public void  run ()  {            system.out.println ( Thread.CurrentThread (). GetName ()  +  "executing. ");             try { &nbSp;              thread.sleep (100);             } catch  ( Interruptedexception e)  {                 e.printstacktrace ();             }        }    }}


Java multithreading-new features-thread pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.