Learning of Java's concurrent programming thread pool

Source: Internet
Author: User

If the number of concurrent threads is large, and each thread is executing a short task, then the frequent creation of threads can greatly reduce the efficiency of the system because it takes time to create threads and destroy threads frequently.

The Java.uitl.concurrent.ThreadPoolExecutor class is the most central class in a thread pool.

Corepoolsize in many places is translated into the core pool size, in fact, I understand this is the size of the thread pool. To give a simple example:

 If there is a factory, there are 10 workers in the factory, each worker can only do one task at the same time.

So as long as 10 workers are idle, the task is assigned to the idle workers;

When 10 workers have a task to do, if the task is still in the queue to wait for the task;

If the number of new tasks is growing much faster than the workers do, then the factory supervisor may want to remedy the situation, such as re-recruit 4 temporary workers to come in;

The task is then assigned to the 4 temporary workers;

If it is not enough to say that 14 workers are doing the task, the factory supervisor may want to consider no longer accepting new tasks or abandoning some of the previous tasks.

When one of the 14 workers is free, and the new task grows at a slower pace, the factory manager may consider quitting 4 temporary workers, keeping the original 10, after all, to ask for extra workers to spend money.

The corepoolsize in this example is 10, and Maximumpoolsize is 14 (10+4).

That is, Corepoolsize is the size of the thread pool, and maximumpoolsize, in my opinion, is a remedial measure of the thread pool, that is, when the task volume is suddenly too large.

However, to facilitate understanding, Corepoolsize is translated into core pool size later in this article.

Largestpoolsize is just a variable used to record the maximum number of threads that have ever been in a thread pool, with no relation to the capacity of the thread pools.

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).

(1) 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. The sample code is as follows:

  1. Package test;
  2. Import Java.util.concurrent.ExecutorService;
  3. Import java.util.concurrent.Executors;
  4. Public class Threadpoolexecutortest {
  5. public static void Main (string[] args) {
  6. Executorservice Cachedthreadpool = Executors.newcachedthreadpool ();
  7. For (int i = 0; i < i++) {
  8. final int index = i;
  9. try {
  10. Thread.Sleep (Index * 1000);
  11. } catch (Interruptedexception e) {
  12. E.printstacktrace ();
  13. }
  14. Cachedthreadpool.execute (new Runnable () {
  15. public Void Run () {
  16. SYSTEM.OUT.PRINTLN (index);
  17. }
  18. });
  19. }
  20. }
  21. }   

The thread pool is infinitely large, and when the first task is completed when the second task is performed, the threads that perform the first task are reused instead of each new thread.

(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:

  1. Package test;
  2. Import Java.util.concurrent.ExecutorService;
  3. Import java.util.concurrent.Executors;
  4. Public class Threadpoolexecutortest {
  5. public static void Main (string[] args) {
  6. Executorservice Fixedthreadpool = Executors.newfixedthreadpool (3);
  7. For (int i = 0; i < i++) {
  8. final int index = i;
  9. Fixedthreadpool.execute (new Runnable () {
  10. public Void Run () {
  11. try {
  12. SYSTEM.OUT.PRINTLN (index);
  13. Thread.Sleep (2000);
  14. } catch (Interruptedexception e) {
  15. E.printstacktrace ();
  16. }
  17. }
  18. });
  19. }
  20. }
  21. }


Because the thread pool size is 3, each task outputs index after sleep for 2 seconds, so 3 digits are printed every two seconds.
The size of a fixed-length pool is best set based on system resources. such as Runtime.getruntime (). Availableprocessors ().

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

Java code
  1. Package test;
  2. Import java.util.concurrent.Executors;
  3. Import Java.util.concurrent.ScheduledExecutorService;
  4. Import Java.util.concurrent.TimeUnit;
  5. Public class Threadpoolexecutortest {
  6. public static void Main (string[] args) {
  7. Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5);
  8. Scheduledthreadpool.schedule (new Runnable () {
  9. public Void Run () {
  10. SYSTEM.OUT.PRINTLN ("delay 3 seconds");
  11. }
  12. }, 3, timeunit.seconds);
  13. }
  14. }


Represents a delay of 3 seconds for execution.

The sample code is executed periodically as follows:

Java code
  1. Package test;
  2. Import java.util.concurrent.Executors;
  3. Import Java.util.concurrent.ScheduledExecutorService;
  4. Import Java.util.concurrent.TimeUnit;
  5. Public class Threadpoolexecutortest {
  6. public static void Main (string[] args) {
  7. Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5);
  8. Scheduledthreadpool.scheduleatfixedrate (new Runnable () {
  9. public Void Run () {
  10. SYSTEM.OUT.PRINTLN ("Delay 1 seconds, and excute every 3 seconds");
  11. }
  12. }, 1, 3, timeunit.seconds);
  13. }
  14. }

Represents a delay of 1 seconds after every 3 seconds.

(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:

Java code
  1. Package test;
  2. Import Java.util.concurrent.ExecutorService;
  3. Import java.util.concurrent.Executors;
  4. Public class Threadpoolexecutortest {
  5. public static void Main (string[] args) {
  6. Executorservice singlethreadexecutor = Executors.newsinglethreadexecutor ();
  7. For (int i = 0; i < i++) {
  8. final int index = i;
  9. Singlethreadexecutor.execute (new Runnable () {
  10. public Void Run () {
  11. try {
  12. SYSTEM.OUT.PRINTLN (index);
  13. Thread.Sleep (2000);
  14. } catch (Interruptedexception e) {
  15. E.printstacktrace ();
  16. }
  17. }
  18. });
  19. }
  20. }
  21. }


The results are output sequentially, which is equivalent to performing each task sequentially.

Learning of Java's concurrent programming 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.