Java common thread pool

Java provides four thread pools through Executors:
newCachedThreadPool creates a cacheable thread pool. If the length of the thread pool exceeds the processing requirement, idle threads can be flexibly recovered. If there is no recovery, a new thread will be created.
newFixedThreadPool creates a fixed-length thread pool, which can control the maximum number of concurrent threads, and the excess threads will wait in the queue.
newScheduledThreadPool creates a fixed-length thread pool that supports scheduled and periodic task execution.
newSingleThreadExecutor creates a single-threaded thread pool that only uses a single worker thread to execute tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

 

(1) newCachedThreadPool
creates a cacheable thread pool. If the length of the thread pool exceeds the processing needs, it can flexibly recycle idle threads. If there is no recovery, create a new thread. The sample code is as follows:

Java code   Favorite 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 cachedThreadPool = Executors.newCachedThreadPool();  
  7.   for (int i = 0; i < 10; 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 infinite. When the second task is executed, the first task has been completed, and the thread executing the first task will be reused instead of creating a new thread each time.
 
(2) newFixedThreadPool
creates a fixed-length thread pool, which can control the maximum number of concurrent threads, and the excess threads will wait in the queue. The sample code is as follows:

Java code   Favorite 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 fixedThreadPool = Executors.newFixedThreadPool(3);  
  7.   for (int i = 0; i < 10; 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 sleeps for 2 seconds after outputting the index, so 3 numbers are printed every two seconds.
The size of the fixed-length thread pool is best set according to system resources. Such as Runtime.getRuntime().availableProcessors()

 

(3) newScheduledThreadPool
creates a fixed-length thread pool to support timing and periodic task execution. The sample code for delayed execution is as follows:

Java code   Favorite 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. }  

 
Indicates a delay of 3 seconds to execute.

Regularly execute the sample code as follows:

Java code   Favorite 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. }  

 
Indicates that it will be executed every 3 seconds after a delay of 1 second.

 

(4) newSingleThreadExecutor
creates a single-threaded thread pool, which only uses a single worker thread to execute tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority). The sample code is as follows:

Java code   Favorite 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 < 10; 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 in sequence, which is equivalent to executing each task in sequence.

You can use the monitoring tool that comes with JDK to monitor the number of threads we create, run a non-terminating thread, create a specified number of threads, and observe:
Tools directory: C:\Program Files\Java\jdk1.6.0_06\bin The \jconsole.exe
running program is slightly modified:

Java code   Favorite 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.newCachedThreadPool();  
  7.   for (int i = 0; i < 100; i++) {  
  8.    final int index = i;  
  9.    singleThreadExecutor.execute(new Runnable() {  
  10.     public void run() {  
  11.      try {  
  12.       while(true) {  
  13.        System.out.println(index);  
  14.        Thread.sleep(10 * 1000);  
  15.       }  
  16.      } catch (InterruptedException e) {  
  17.       e.printStackTrace ();  
  18.      }  
  19.     }  
  20.    });  
  21.    try {  
  22.     Thread.sleep(500);  
  23.    } catch (InterruptedException e) {  
  24.     e.printStackTrace ();  
  25.    }  
  26.   }  
  27.  }  
  28. }  

 
The effect is as follows:

 

Select the program we run:

Monitor operating status

 

 

Reference link: http://cuisuqiang.iteye.com/blog/2019372

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325097930&siteId=291194637