Java thread pool Executorservice detailed and instance code _java

Source: Internet
Author: User
Tags terminates

Java thread Pool Executorservice

1. Thread pool 

1.1 What happens when you use the thread pool

    1. A single task has a relatively short time to process.
    2. The number of tasks that will need to be handled is large.

1.2 Benefits of using a thread pool

    1. Reduce the time spent on creating and destroying threads and the overhead of system resources.
    2. If you do not use a thread pool, it is possible that the system creates a large number of threads that consume system memory and "over switch";

2.ExecutorService and executors

2.1 Introduction

Executorservice is an interface that inherits the executor,

Public interface Executorservice extend executor{
}

Executor is also an interface that contains only one method:

Public interface Executor {
  void execute (Runnable command);
}

The top-level interface of the thread pool in Java is excutor, but in the strictest sense >>exector is not a thread pool, but a tool for executing threads, and the real thread > Pool interface is executorservice.

3.Executors

It is a static factory class, it can produce different types of thread pool, part of the source code is as follows:

public class Executors {
//newfixedthreadpool public
static executorservice newfixedthreadpool (int nthreads) { return
    new Threadpoolexecutor (Nthreads, Nthreads, 0L, Timeunit.milliseconds,new linkedblockingqueue<runnable > ());
}
Newcachethreadpool public
 static Executorservice Newcachedthreadpool () {return
    new Threadpoolexecutor (0, integer.max_value,60l, Timeunit.seconds,new synchronousqueue<runnable> ());
  }
 Newscheduledthreadpool public
  static scheduledexecutorservice newscheduledthreadpool (int corepoolsize) { return
    new Scheduledthreadpoolexecutor (corepoolsize);
  }
  Newstringooo
}

Let's take a look at a concrete example to illustrate the similarities and differences between them.

Package thread;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.ScheduledExecutorService;
 /** * Created by Yang on 16-7-11.  * * Public class Ch09_executor {private static void run (Executorservice threadPool) {for (int i = 1; i < 5; i++)
      {Final int taskid=i;
            Threadpool.execute (New Runnable () {@Override public void run () {for (int i=1;i<5;i++) {
            try{Thread.Sleep (20);
            }catch (interruptedexception e) {e.printstacktrace ();
          } System.out.println ("+taskid+", "+i+", "Second Execution");
    }
        }
      });

  } threadpool.shutdown (); public static void Main (string[] args) {//Create a thread pool that can hold 3 threads executorservice fixedthreadpool= executors.newfixed
    ThreadPool (3);
    The size of the thread pool is dynamically assigned Executorservice Cachethreadpool=executors.newcachedthreadpool () According to the task being performed; Create a thread pool of individual threads, such asIf the current thread is suddenly interrupted while the task is executing, a new thread is created to replace it.
    Executorservice Singlethreadpool=executors.newsinglethreadexecutor ();
    The effect is similar to the timer timer Scheduledexecutorservice Scheduledthreadpool=executors.newscheduledthreadpool (3); Run (Fixedthreadpool); (1)//run (Cachethreadpool); (2)//Run (Singlethreadpool); (3)//Run (Scheduledthreadpool);

 (4)}}

4.4 kinds of common thread pools

4.1 Cachedthreadpool

Cachedthreadpool creates a buffer that caches the initialized thread, terminates and removes the thread from the cache that has been unused for 6 seconds.
If the thread is available, use the thread that was previously created. If the thread is not available, a new thread is created.

. Reuse:

Buffer pool, first see if there are any previously established threads in the pool, if so, just reuse, if not, create a new thread to join the pool,

Usage scenarios:

Cache pools are typically used to perform asynchronous tasks with short lifetimes, so there are few uses for connection-oriented daemon servers.

Timeout:

A thread that can be reuse must be a timeout within the idle, the default timeout is 60s, longer than this idle, and the thread instance will be terminated and removed from the pool.

End:

The thread that puts the Cachedthreadpool does not have to worry about its end, more than timeout inactive, and it will be automatically terminated.

Instance Explanation:

Remove (2) The annotation, run, get the results of the run as follows:

The 1th time of the 1th task, the 1th execution of the 3rd task, the 2nd time of the 1th task of the 4th sub-mission, and the third-time execution of the 1th of the third-time mandate, which is performed in the 3rd of the 2nd sub-tasks for the third time.
The
2nd execution of the 4th task,
3rd
Execution of the 3rd task, the 1th of the 3rd, the 2nd of the 3rd, and the 4th execution of the 3rd sub-task. 2nd mandate 4th Execution of the
4th mandate 4th execution
of the 1th task of the third time

As you can see from the results, 4 tasks are performed alternately.

4.2FixedThreadPool

In the Fixedthreadpool, there is a pool of fixed size,

If the task currently required exceeds the pool size, the extra task is waiting until there are idle threads executing the task.
If the currently required task is smaller than the pool size, the idle thread is not destroyed.

Reuse:

Fixedthreadpool and Cachethreadpool are similar, but also can be used reuse, but can not build a new thread at any time

Fixed number

Its uniqueness is that at any point in time, only a fixed number of active threads exist, at which point if a new thread is to be established, it can only be placed in another queue until a thread in the current thread terminates and is moved directly out of the pool.

Timeout:

Unlike Cachethreadpool, Fixedthreadpool has no idle mechanism.

Usage scenarios:

So Fixedthreadpool is mostly for some very stable, regular concurrent threads, mostly for servers.

SOURCE Analysis:

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)
Cache Pool Threads Support 0-integer.max_value (apparently not considering host resource affordability), 60 seconds idle

Instance Explanation:

Remove the annotation (1) and run the following results:

The 1th time of the 1th task, the 1th execution of the 3rd task, the 2nd time of the 1th task of the 1th sub-mission, and the third-time execution of the 2nd of the third-time mandate, which is performed in the 3rd of the 2nd sub-tasks for the third time.
The
3rd execution of the 3rd task,
3rd
Execution of the 2nd task, the 1th of the 4th, the 3rd of the 4th, and the 2nd execution of the 4th sub-task. 4th mandate 2nd Execution of the
4th mandate 3rd execution
of the 4th task of the third time

Creates a fixed size thread pool with a capacity of 3 and then loops through 4 tasks, and as you can see from the output, the first 3 tasks are executed, and then the idle threads perform the 4th task.

4.3SingleThreadExecutor

    1. Singlethreadexector gets a single thread that will ensure that your task executes.
    2. Single thread, there can be only one thread in any time pool
    3. If the current thread terminates unexpectedly, a new thread is created to continue the task, unlike the one we created directly, and the Newfixedthreadpool (1).
    4. Uses the same bottom pool as the cache and fixed pools, but the number of threads is 1-1, 0 seconds idle (no idle)

Remove (3) the comment. See implementation results as follows:

The 1th time of the 1th task, the 2nd execution of the 1th task, the 1th time of the 3rd task of the 1th sub-mission, and the third-time execution of the 4th of the third-time mandate, which is performed in the 2nd of the 1th sub-tasks for the third time.
The
4th execution of the 2nd task,
1th
Execution of the 3rd task, the 3rd of the 2nd, the 3rd of the 3rd, and the 3rd execution of the 4th sub-task. 4th mandate 2nd Execution of the
4th mandate 3rd execution
of the 4th task of the third time

The four tasks are executed sequentially.

4.4 Scheduledthreadpool

Scheduledthreadpool is a fixed size thread pool, similar to Fixedthreadpool, which performs tasks that are timed tasks.
Get rid of (4) of the annotation results and fixedthreadpool get the same result, scheduledthreadpool mainly not here, but timed task, look at the following example:

Package thread;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;

Import Java.util.concurrent.TimeUnit;
 /** * Created by Yang on 16-7-11.
  * * Public class Myscheduledtask implements Runnable {private String tname;
  Public Myscheduledtask (String name) {this.tname=name;

  The public void Run () {System.out.println (tname+ "task is 2 seconds delay execution!");
    public static void Main (string[] args) {scheduledexecutorservice scheduledpool= executors.newscheduledthreadpool (2);
    Scheduledexecutorservice Singschedulepool=executors.newsinglethreadscheduledexecutor ();
    Myscheduledtask mt1=new myscheduledtask ("MT1");
    Myscheduledtask mt2=new myscheduledtask ("mt2");
    Start MT1 Task Execution Scheduledpool.schedule (mt1,2, timeunit.seconds) with Scheduledthreadpool;
    Start mt2 with Singlescheduledthreadpool;
    Singschedulepool.schedule (Mt2,2000,timeunit.milliseconds);
    Scheduledpool.shutdown ();
  Singschedulepool.shutdown ();

 }
}

Results:

MT1 task time delay 2 seconds to execute!
MT2 task time delay 2 seconds to execute!

After the program runs for 2 seconds, the results are displayed, indicating that the thread was executed after 2 seconds.

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

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.