Thread pool Executors detailed

Source: Internet
Author: User
Tags connection pooling

Why use a thread pool?

One is to reduce the number of creation and destruction of threads, each worker can be reused to perform multiple tasks;
Second, you can adjust the number of threads in the thread pool according to the ability of the system, to prevent the server from being exhausted because of excessive memory consumption (approximately 1MB of memory per thread, the more threads open, the more memory is consumed, and the last crashes).

The basic idea of thread pool is a kind of object pooling idea, which opens up a memory space, which contains many (not dead) threads, and the pool 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.

As can be seen, the role of the thread pool is primarily to limit the number of threads executing in the system. Depending on the environment of the system, the number of threads can be set automatically or manually to achieve the best performance. This is because, fewer threads will waste system resources, more threads will cause the system congestion, efficiency is not high. Use the thread pool to control the number of threads and other threads to wait. A task is completed, and then the first task from the queue starts executing. If there is no waiting process in the queue, this resource of the thread pool is waiting. When a new task needs to run, it can start running if there are waiting worker threads in the thread pool, otherwise enter the wait queue.

The top interface of the thread pool in Java is executor, but strictly speaking, executor is not a thread pool, but a tool for executing threads. The real thread pool interface is executorservice. Threadpoolexecutor is the underlying implementation of the Executors class. Let's first introduce the next executors.

Before using the thread pool, you must know how to create a thread pool.

1. Fixed-size thread pool  

Package Com.itszt.test3;import java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * thread pool */public class Test1 extends  object{public    static void Main (string[] args) {        //Create a reusable thread pool        that has a fixed number of threads Executorservice ThreadPool = Executors.newfixedthreadpool (2);        Create a class that implements the Runnable interface, such as thread        MyThread t1 = new MyThread ();        MyThread t2 = new MyThread ();        MyThread t3 = new MyThread ();        MyThread T4 = new MyThread ();        Put the thread into the pool to execute        threadpool.execute (t1);        Threadpool.execute (T2);        Threadpool.execute (T3);        Threadpool.execute (T4);        Close the thread pool        threadpool.shutdown ();    }} Class MyThread extends thread{    @Override public    void Run () {        System.out.println (Thread.CurrentThread ( ). GetName () + "executing ...");}    

The results of the implementation are as follows:

Pool-1-thread-1 is executing ... pool-1-thread-2 executing ... pool-1-thread-1 executing ... pool-1-thread-1 is executing ...

2. Single Task thread pool

To reuse the code above, change the code in the example above to create the thread pool:

Executorservice ThreadPool = Executors.newsinglethreadexecutor ();

The results of the implementation are as follows:

Pool-1-thread-1 is executing ... pool-1-thread-1 executing ... pool-1-thread-1 executing ... pool-1-thread-1 is executing ...

3. Variable-size thread pool

To change the way the thread pool is created:

Executorservice ThreadPool = Executors.newcachedthreadpool ();

The results of the implementation are as follows:

Pool-1-thread-2 is executing ... pool-1-thread-1 executing ... pool-1-thread-3 executing ... pool-1-thread-4 is executing ...

4. Delay connection Pooling

To modify how the thread pool is created:

Scheduledexecutorservice ThreadPool = Executors.newscheduledthreadpool (2); MyThread T1 = new MyThread (); MyThread t2 = new MyThread (); MyThread t3 = new MyThread (); MyThread T4 = new MyThread ();//deferred execution Threadpool.schedule (t1,5, timeunit.milliseconds); Threadpool.schedule (t2,5, Timeunit.milliseconds); Threadpool.schedule (t3,5, timeunit.milliseconds); Threadpool.schedule (t4,5, Timeunit.milliseconds);//close thread pool Threadpool.shutdown ();

5. Single-Task deferred connection pooling

To modify how the thread pool is created:

Scheduledexecutorservice ThreadPool = Executors.newsinglethreadscheduledexecutor ();        

6. Custom thread pool

Package Com.itszt.test3;import Java.text.simpledateformat;import Java.util.date;import Java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.threadpoolexecutor;import java.util.concurrent.timeunit;/** * Custom thread pool */public class Test2 {Publi        c static void Main (string[] args) {//Create wait queue blockingqueue Bqueue = new Arrayblockingqueue (20);        Create a single-threaded execution program that can schedule threadpoolexecutor pool = new Threadpoolexecutor (2,3,2,timeunit.milliseconds,bqueue) after a given delay time;        Create a class that implements the Runnable interface, such as thread MyThread t1 = new MyThread ();        MyThread t2 = new MyThread ();        MyThread t3 = new MyThread ();        MyThread T4 = new MyThread ();        Put the thread into the pool to execute pool.execute (T1);        Pool.execute (T2);        Pool.execute (T3);        Pool.execute (T4);    Close the thread pool Pool.shutdown (); }}class MyThread extends thread{@Override public void Run () {System.out.println (Thread.CurrentThread (). GetName () + "Executing ..." +system.currenttimemillis ());   }}

Thread pool Executors detailed

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.