Use of 4 thread pools created by executors

Source: Internet
Author: User

Java provides four thread pools through executors, namely:
Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.
Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.
Newsinglethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

Note: The thread pool is only intended to control the probability that an application is dealing with a thread that is unsafe to prevent high concurrency problems in a business. In my current test, I have not found that the thread can reuse this concept, because after the thread is opened, it is closed, can not be opened again, view source discovery will be created each time a new thread to process the business. The thread pool can be used to specify the maximum number of synchronization threads to handle this business, such as:Executors.newfixedthreadpool (3), and three threads in thread pooling can be executed at the same time, but note that this is not to say that the threads pool is always the three threads. Just say the number of threads that can exist at the same time, and when a thread finishes executing, a new thread will come in. Newfixedthreadpool.execute (New threadforpools ()); The implication of this sentence is not to add a new thread, but to add a new processing business request in. At least I now understand that there are no threads that can be reused.

To process thread code:

Package com.alivn.sockets;/** * Created by ALIVN on 2017/3/19. */public class Threadforpools implements runnable{    private Integer index;    Public  threadforpools (Integer index)    {     this.index=index;    }    @Override public    Void Run () {        /***         * Business ... Omit          *        /try {            System.out.println ("Start processing thread!!! ");            Thread.Sleep (index*100);            System.out.println ("My thread ID is:" +this.tostring ());        } catch (Interruptedexception e) {            e.printstacktrace ();}}    }

(1) Newcachedthreadpool
Create a cacheable thread pool in which the number of threads present in the application can be infinitely large

The sample code is as follows:

Package Com.alivn.sockets;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * Created by Alivn on 2017/3/19. */public class Threadpools {    /**     * We get four times threads, observe 4 thread addresses     * @param args */     public    static  void main (String[]args)    {        Executorservice Newcachedthreadpool = Executors.newcachedthreadpool ();        System.out.println ("****************************newcachedthreadpool*******************************");        for (int i=0;i<4;i++)        {            final int index=i;          Newcachedthreadpool.execute (New Threadforpools (index));}}}    

The output is: there can be infinitely large number of threads coming in (different thread addresses)

(2) Newfixedthreadpool
Creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue. The sample code is as follows:

Package Com.alivn.sockets;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * Created by Alivn on 2017/3/19. */public class Threadpools {    /**     * We get four times threads, observe 4 thread addresses     * @param args */     public    static  void main (String[]args)    {        //thread pool allows simultaneous presence of two threads        executorservice newfixedthreadpool = Executors.newfixedthreadpool (2);        System.out.println ("****************************newfixedthreadpool*******************************");        for (int i=0;i<4;i++)        {            final int index=i;            Newfixedthreadpool.execute (New Threadforpools (index));}}}    

Output: Only two threads are processed at a time, and when the first thread finishes executing, the new thread comes in and starts processing (the thread address is not the same)

(3) Newscheduledthreadpool
Create a fixed-line pool that supports timed and recurring task execution. The deferred execution sample code is as follows:

Package Com.alivn.sockets;import Java.util.concurrent.executors;import Java.util.concurrent.scheduledexecutorservice;import java.util.concurrent.timeunit;/** * Created by ALIVN on 2017/3/ */public class Threadpools {    /**     * We get four times threads, observe 4 thread addresses     * @param args */public    static  void Main (String[]args)    {        Scheduledexecutorservice newscheduledthreadpool = Executors.newscheduledthreadpool (2 );        System.out.println ("****************************newfixedthreadpool*******************************");        for (int i=0;i<4;i++)        {            final int index=i;            Delay three seconds Execution            Newscheduledthreadpool.schedule (new Threadforpools (index), 3, timeunit.seconds);}}}    

Execution result: Deferred three seconds after execution, in addition to deferred execution and Newfixedthreadpool basically the same, can be used to perform scheduled tasks

4) Newsinglethreadexecutor
Creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority). The sample code is as follows:

 PackageCom.alivn.sockets;importJava.util.concurrent.executorservice;importJava.util.concurrent.executors;importJava.util.concurrent.scheduledexecutorservice;importjava.util.concurrent.timeunit;/*** Created by ALIVN on 2017/3/19.*/public classThreadpools {/*** We get four times threads, observe 4 thread addresses *@paramargs */public static voidMain (String[]args) {Executorservice newsinglethreadexecutor =Executors.newsinglethreadexecutor (); System.out.println ("****************************newfixedthreadpool*******************************"); for (int i=0;i<4;i++) {Final int index=i; Newsinglethreadexecutor.execute (NewThreadforpools (index)); }    }}

Execution result: Only one thread exists, sequential execution

Transferred from: https://www.cnblogs.com/ljp-sun/p/6580147.html

Use of 4 thread pools created by executors

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.