Thread pool (detailed): three methods, seven parameters, four rejection strategies

Keywords: Java

Thread pool (focus)

Thread pool: three methods, seven parameters, four rejection strategies

Pooling technology:
01: The operation of the program, essence: occupy system resources!Optimize the use of resources!=>Pooling Technology
02: Thread pool, connection pool, memory pool, object pool //... created, destroyed.Very wasteful of resources
03: Pooling technology: Prepare some resources in advance. If someone wants to use them, come here to pick them up and return them to me when they are finished.
The benefits of thread pooling:
01: Reduce resource consumption
02: Increase response speed
03: Easy to manage
(Key) Thread Reuse, Control Maximum Concurrency, Manage Threads
Two: Three main methods:

01:Executors.newSingleThreadExecutor() //Single Thread
* Code Sample 01
 1 package pool;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 
 6 //Executors Tool classes, three main methods
 7 
 8 public class Demo01 {
 9     public static void main(String[] args) {
10 
11         ExecutorService threadpool = Executors.newSingleThreadExecutor();     //Single Thread
12 
13         try {
14             for (int i = 0; i < 10; i++) {
15                 //After using thread pools, use thread pools to create threads
16                 threadpool.execute(()->{
17                     System.out.println(Thread.currentThread().getName()+" ok");
18                 });
19             }
20         } catch (Exception e) {
21             e.printStackTrace();
22         } finally {
23             //Thread pool exhausted, program ended, thread pool closed
24             threadpool.shutdown();   //(To ensure shutdown, place the shutdown method in the finally Medium)
25         }
26     }
27 }

Run result: (10 tasks are operated on by the same thread)

  

02:newFixedThreadPool(int nThreads) //Create a fixed thread pool size

* Code Sample 02

 1 package pool;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 
 6 //Executors Tool classes, three main methods
 7 
 8 public class Demo01 {
 9     public static void main(String[] args) {
10 
11         //Up to five threads execute simultaneously, viewing results from the console
12         ExecutorService threadpool = Executors.newFixedThreadPool(5);   //Create a fixed thread pool size, (5 threads)
13 
14         try {
15             for (int i = 0; i < 10; i++) {
16                 //After using thread pools, use thread pools to create threads
17                 threadpool.execute(()->{
18                     System.out.println(Thread.currentThread().getName()+" ok");
19                 });
20             }
21         } catch (Exception e) {
22             e.printStackTrace();
23         } finally {
24             //Thread pool exhausted, program ended, thread pool closed
25             threadpool.shutdown();   //(To ensure shutdown, place the shutdown method in the finally Medium)
26         }
27     }
28 }

Run result: (up to 5 threads executing at the same time)

 

03:newCachedThreadPool //Cache pool, scalable, strong when strong, weak when weak

* Code Sample 03

 1 package pool;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 
 6 //Executors Tool classes, three main methods
 7 
 8 public class Demo01 {
 9     public static void main(String[] args) {
10 
11         ExecutorService threadpool = Executors.newCachedThreadPool();   //Cache pool, scalable, strong when strong, weak when weak
12 
13         try {
14             for (int i = 0; i < 10; i++) {
15                 //After using thread pools, use thread pools to create threads
16                 threadpool.execute(()->{
17                     System.out.println(Thread.currentThread().getName()+" ok");
18                 });
19             }
20         } catch (Exception e) {
21             e.printStackTrace();
22         } finally {
23             //Thread pool exhausted, program ended, thread pool closed
24             threadpool.shutdown();   //(To ensure shutdown, place the shutdown method in the finally Medium)
25         }
26     }
27 }

Run result: (10 threads executing at the same time, scalable, strong when strong, weak when weak)

 

 

Three: Seven parameters

01: Source analysis of the three main methods:

 1      (1)  newSingleThreadExecutor()              //Single Thread
 2 
 3         public static ExecutorService newSingleThreadExecutor() {
 4                 return new FinalizableDelegatedExecutorService
 5                     (new ThreadPoolExecutor(1, 1,
 6                                             0L, TimeUnit.MILLISECONDS,
 7                                             new LinkedBlockingQueue<Runnable>()));
 8             }
 9         ==================================================================================
10         (2)  newFixedThreadPool(int nThreads)       //Create a fixed thread pool size
11 
12         public static ExecutorService newFixedThreadPool(int nThreads) {
13                 return new ThreadPoolExecutor(nThreads, nThreads,
14                                               0L, TimeUnit.MILLISECONDS,
15                                               new LinkedBlockingQueue<Runnable>());
16             }
17         ===================================================================================
18         (3)  newCachedThreadPool()                  //Cache pool, scalable, strong when strong, weak when weak
19 
20         public static ExecutorService newCachedThreadPool() {
21                 return new ThreadPoolExecutor(0, Integer.MAX_VALUE,     //Integer.Max_VALUE  About 2.1 billion  //If we had so many threads running together, the computer would OOM(overflow),Problem
22                                               60L, TimeUnit.SECONDS,                          
23                                               new SynchronousQueue<Runnable>());             
24             }
25         ====================================================================================
26         (4) Common to all three methods  ThreadPoolExecutor() Method
27 
28                                         ******7 Large parameters******
29 
30         public ThreadPoolExecutor(int corePoolSize,                         //Core thread pool size
31                                       int maximumPoolSize,                  //Maximum Core Thread Pool Size
32                                       long keepAliveTime,                   //Timeout will be released if no one calls it
33                                       TimeUnit unit,                        //Timeout Unit
34                                       BlockingQueue<Runnable> workQueue,    //Blocking Queue
35                                       ThreadFactory threadFactory,          //Thread factory, which creates threads, normally without action
36                                       RejectedExecutionHandler handler) {   //Rejection Policy
37                 if (corePoolSize < 0 ||
38                     maximumPoolSize <= 0 ||
39                     maximumPoolSize < corePoolSize ||
40                     keepAliveTime < 0)
41                     throw new IllegalArgumentException();
42                 if (workQueue == null || threadFactory == null || handler == null)
43                     throw new NullPointerException();
44                 this.corePoolSize = corePoolSize;
45                 this.maximumPoolSize = maximumPoolSize;
46                 this.workQueue = workQueue;
47                 this.keepAliveTime = unit.toNanos(keepAliveTime);
48                 this.threadFactory = threadFactory;
49                 this.handler = handler;
50             }

 

The Alibaba Development Manual contains the following provisions:

 

For example, bank business map:

Four rejection strategies:


/**
* NEWThreadPoolExecutor.AbortPolicy() // The bank is full, and someone else comes in and doesn't handle this person, throws an exception
* NEWThreadPoolExecutor.CallerRunsPolicy() / /Where and where to come!
* NEWThreadPoolExecutor.DiscardPolicy() // The queue is full. Throw away the task without throwing an exception!
* NEWThreadPoolExecutor.DiscardOldestPolicy() // The queue is full, try and compete the earliest, and won't throw an exception
*/

5: Create a thread pool manually (custom):
 

Code Sample 01 > NewThreadPoolExecutor.AbortPolicy() // The bank is full and someone else comes in and throws an exception if they don't handle this person
 1 package pool;
 2 
 3 import java.util.concurrent.Executors;
 4 import java.util.concurrent.LinkedBlockingDeque;
 5 import java.util.concurrent.ThreadPoolExecutor;
 6 import java.util.concurrent.TimeUnit;
 7 
 8 public class Demo02 {
 9     public static void main(String[] args) {
10         //Custom Thread Pool!Only use in work ThreadPoolExecutor
11         ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
12                 2,                                  //Core thread pool size
13                 5,                             //Maximum Core Thread Pool Size
14                 3,                                //Timeout will be released if no one calls it
15                 TimeUnit.SECONDS,                               //Timeout Unit
16                 new LinkedBlockingDeque<>(3),          //Blocking Queue
17                 Executors.defaultThreadFactory(),               //Thread factory, which creates threads, normally without action
18                 new ThreadPoolExecutor.AbortPolicy());  //The bank is full and there are people coming in who don't handle this person and throw an exception
19 
20         try {
21             //Maximum number of bearings, Deque + Max    (Number of Queue Threads+Maximum Threads)
22             //Overthrow RejectedExecutionException abnormal
23             for (int i = 1; i <= 9; i++) {
24                 //After using thread pools, use thread pools to create threads
25                 threadPool.execute(()->{
26                     System.out.println(Thread.currentThread().getName()+" ok");
27                 });
28             }
29         } catch (Exception e) {
30             e.printStackTrace();
31         } finally {
32             //Thread pool exhausted, program ended, thread pool closed
33             threadPool.shutdown();      //(To ensure shutdown, place the shutdown method in the finally Medium)
34         }
35     }
36 }

Running results (comparison):

     

     

 

Code Sample 02 NewThreadPoolExecutor.CallerRunsPolicy() Where to/ Where to come

 1 package pool;
 2 
 3 import java.util.concurrent.Executors;
 4 import java.util.concurrent.LinkedBlockingDeque;
 5 import java.util.concurrent.ThreadPoolExecutor;
 6 import java.util.concurrent.TimeUnit;
 7 
 8 public class Demo02 {
 9     public static void main(String[] args) {
10         //Custom Thread Pool!Only use in work ThreadPoolExecutor
11         ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
12                 2,                                  //Core thread pool size
13                 5,                             //Maximum Core Thread Pool Size
14                 3,                                //Timeout will be released if no one calls it
15                 TimeUnit.SECONDS,                               //Timeout Unit
16                 new LinkedBlockingDeque<>(3),          //Blocking Queue
17                 Executors.defaultThreadFactory(),               //Thread factory, which creates threads, normally without action
18                 new ThreadPoolExecutor.CallerRunsPolicy());     //Where to come and where to go!
19 
20         try {
21             //Maximum number of bearings, Deque + Max    (Number of Queue Threads+Maximum Threads)
22             //Overthrow RejectedExecutionException abnormal
23             for (int i = 1; i <= 9; i++) {
24                 //After using thread pools, use thread pools to create threads
25                 threadPool.execute(()->{
26                     System.out.println(Thread.currentThread().getName()+" ok");
27                 });
28             }
29         } catch (Exception e) {
30             e.printStackTrace();
31         } finally {
32             //Thread pool exhausted, program ended, thread pool closed
33             threadPool.shutdown();      //(To ensure shutdown, place the shutdown method in the finally Medium)
34         }
35     }
36 }

Run result:

 

Code Sample 03 NewThreadPoolExecutor.DiscardPolicy() // The queue is full. Throw away the task without throwing an exception!

 1 package pool;
 2 
 3 import java.util.concurrent.Executors;
 4 import java.util.concurrent.LinkedBlockingDeque;
 5 import java.util.concurrent.ThreadPoolExecutor;
 6 import java.util.concurrent.TimeUnit;
 7 
 8 public class Demo02 {
 9     public static void main(String[] args) {
10         //Custom Thread Pool!Only use in work ThreadPoolExecutor
11         ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
12                 2,                                  //Core thread pool size
13                 5,                             //Maximum Core Thread Pool Size
14                 3,                                //Timeout will be released if no one calls it
15                 TimeUnit.SECONDS,                               //Timeout Unit
16                 new LinkedBlockingDeque<>(3),          //Blocking Queue
17                 Executors.defaultThreadFactory(),               //Thread factory, which creates threads, normally without action
18                 new ThreadPoolExecutor.DiscardPolicy());        //The queue is full, throw the task away, no exceptions will be thrown!
19 
20         try {
21             //Maximum number of bearings, Deque + Max    (Number of Queue Threads+Maximum Threads)
22             //Overthrow RejectedExecutionException abnormal
23             for (int i = 1; i <= 9; i++) {
24                 //After using thread pools, use thread pools to create threads
25                 threadPool.execute(()->{
26                     System.out.println(Thread.currentThread().getName()+" ok");
27                 });
28             }
29         } catch (Exception e) {
30             e.printStackTrace();
31         } finally {
32             //Thread pool exhausted, program ended, thread pool closed
33             threadPool.shutdown();      //(To ensure shutdown, place the shutdown method in the finally Medium)
34         }
35     }
36 }

Run result:

 

04: Code Sample * NEWThreadPoolExecutor.DiscardOldestPolicy() // The queue is full, try and compete the earliest, and won't throw an exception

 1 package pool;
 2 
 3 import java.util.concurrent.Executors;
 4 import java.util.concurrent.LinkedBlockingDeque;
 5 import java.util.concurrent.ThreadPoolExecutor;
 6 import java.util.concurrent.TimeUnit;
 7 
 8 public class Demo02 {
 9     public static void main(String[] args) {
10         //Custom Thread Pool!Only use in work ThreadPoolExecutor
11         ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
12                 2,                                  //Core thread pool size
13                 5,                             //Maximum Core Thread Pool Size
14                 3,                                //Timeout will be released if no one calls it
15                 TimeUnit.SECONDS,                               //Timeout Unit
16                 new LinkedBlockingDeque<>(3),          //Blocking Queue
17                 Executors.defaultThreadFactory(),               //Thread factory, which creates threads, normally without action
18                 new ThreadPoolExecutor.DiscardOldestPolicy());  //The queue is full, try and compete the first time, and don't throw an exception
19 
20         try {
21             //Maximum number of bearings, Deque + Max    (Number of Queue Threads+Maximum Threads)
22             //Overthrow RejectedExecutionException abnormal
23             for (int i = 1; i <= 9; i++) {
24                 //After using thread pools, use thread pools to create threads
25                 threadPool.execute(()->{
26                     System.out.println(Thread.currentThread().getName()+" ok");
27                 });
28             }
29         } catch (Exception e) {
30             e.printStackTrace();
31         } finally {
32             //Thread pool exhausted, program ended, thread pool closed
33             threadPool.shutdown();      //(To ensure shutdown, place the shutdown method in the finally Medium)
34         }
35     }
36 }

Run result:

Posted by rami on Thu, 25 Jun 2020 17:45:01 -0700