Several methods and examples of creating various types of thread pools in Java Executors classes __ thread pool

Source: Internet
Author: User

Executors: Provides a series of static factory methods for creating a variety of thread pools. 1.executors.newcachedthreadpool Create a variable thread pool

If the thread pool length exceeds the processing need, the idle thread can be recycled flexibly, and if there is no recyclable, the new thread is created. The core thread pool size is 0, the maximum is integer.max_value, and thread idle survival time is 60 seconds. Sample code:

Executorservice Cachedthreadpool = Executors.newcachedthreadpool ();
        for (int i = 1; I <= 5; i++) {
            final int index = i;
            Cachedthreadpool.execute (()-> {
                System.out.println (index + "start");
                System.out.println (Thread.CurrentThread (). GetName ());
                try {
                    Thread.Sleep (index * 1500);
                } catch (Interruptedexception e) {
                    e.printstacktrace ();
                }
                SYSTEM.OUT.PRINTLN (index + "End");}

Execution Results:

Executors Internal Create Newcachedthreadpool source

public static Executorservice Newcachedthreadpool () {return
        new Threadpoolexecutor (0, Integer.max_value,
                                      60L , Timeunit.seconds,
                                      new synchronousqueue<runnable> ());

2.executors.newfixedthreadpool Create a fixed size thread pool the number of core threads is the maximum number of threads and the thread will not be reclaimed until the shutdown method is invoked to recycle the instance code:

Executorservice Fixedthreadpool = Executors.newfixedthreadpool (2);
	for (int i = 1; I <= 4; i++) {
            final int index = i;
            System.out.println (Thread.CurrentThread (). GetName () + "time" + System.currenttimemillis ());
            Fixedthreadpool.execute (()-> {
                try {
                    System.out.println () Thread.CurrentThread (). GetName () + "time" + System.currenttimemillis ());
                    Thread.Sleep (1500);
                    System.out.println (Thread.CurrentThread (). GetName () + "End");
                catch (Interruptedexception e) {
                    e.printstacktrace ();}}
        );
 
Execution Results:
You can see that two threads are always executing. Executors Internal Create Newfixedthreadpool source
public static Executorservice newfixedthreadpool (int nthreads) {return
        new Threadpoolexecutor (Nthreads, Nthreads,
                                      0L, Timeunit.milliseconds,
                                      new linkedblockingqueue<runnable> ());

3.executors.newscheduledthreadpool Create a timed or recurring task execution thread poolThis thread pool can be used for scheduled or recurring task execution timed Instance code:
Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (2);
    System.out.println (Thread.CurrentThread (). GetName () + "time" + System.currenttimemillis ());
    Execute
    scheduledthreadpool.schedule (()-> {System.out.println () Thread.CurrentThread () after the thread pool is created 3 seconds
        . GetName () + "Time" + System.currenttimemillis ());
        SYSTEM.OUT.PRINTLN ("Delay 3 seconds");
}, 3, timeunit.seconds);
timed execution Results:
Cycle Instance code:
Scheduledexecutorservice schedulethreadpoolatfixedrate = Executors.newscheduledthreadpool (5);
System.out.println (Thread.CurrentThread (). GetName () + "time" + System.currenttimemillis ());
The thread pool is created 1 seconds after execution, followed by a
schedulethreadpoolatfixedrate.scheduleatfixedrate (()-> {System.out.println () every 3 seconds (
      Thread.CurrentThread (). GetName () + "time" + System.currenttimemillis ());
      SYSTEM.OUT.PRINTLN ("Delay 1 seconds, and excute every 3 seconds");
}, 1, 3, timeunit.seconds);
Cycle Execution Results:
Executors Internal Create Newscheduledthreadpool source
public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize) {return
        new Scheduledthreadpoolexecutor (corepoolsize);
 }

Public scheduledthreadpoolexecutor (int corepoolsize) {
        super (corepoolsize, Integer.max_value, 0, nanoseconds,
              new Delayedworkqueue ());
 }
4.executors.singlethreadexecutor Create a single thread poolThe thread pool has, and only one, of the threads performing the task, ensuring that all tasks are performed in the specified order (FIFO, LIFO, priority). Instance code:
Executorservice singlethreadexecutor = Executors.newsinglethreadexecutor ();
	for (int i = 1; I <= 4; i++) {
            final int index = i;
            System.out.println (Thread.CurrentThread (). GetName () + "time" + System.currenttimemillis ());
            Singlethreadexecutor.execute (()-> {
                try {
                    System.out.println () Thread.CurrentThread (). GetName () + "time" + System.currenttimemillis ());
                    Thread.Sleep (1500);
                    System.out.println (Thread.CurrentThread (). GetName () + "End");
                catch (Interruptedexception e) {
                    e.printstacktrace ();}}
        );
Run Result:
Executors Internal Create Newsinglethreadexecutor source
public static Executorservice Newsinglethreadexecutor () {return
        new Finalizabledelegatedexecutorservice
            ( New Threadpoolexecutor (1, 1,
                                    0L, Timeunit.milliseconds,
                                    new Linkedblockingqueue<runnable> ()));
4.executors.newworkstealingpool Create a parallel execution thread poolCreate a thread pool with multiple task queues (in order to reduce the number of connections) Instance code:
Set the parallel level to 2, that is, the default time only 2 threads execute
        executorservice newworkstealingpool = Executors.newworkstealingpool (2);

        for (int i = 1; I <= 4; i++) {
            final int count = i;
            System.out.println ("execute" + i);
            Newworkstealingpool.execute (()-> {
                try {
                    thread.sleep (1000);//this task takes 1s
                    System.out.println ("thread" + Thread.CurrentThread (). GetName () + "complete task:"
                            + count +   time is: "+ system.currenttimemillis ());
                } catch ( Interruptedexception e) {
                    e.printstacktrace ();}}
            );
        
Run Result:
Executors Internal Create Newworkstealingpool source
public static executorservice newworkstealingpool (int parallelism) {return
        new Forkjoinpool
            (parallelism,
             forkjoinpool.defaultforkjoinworkerthreadfactory,
             null, true);
    

Instance code download

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.