The Use of Four Thread Pools in Java

Posted by PAFTprod on Fri, 28 Jun 2019 21:42:45 +0200

Java provides four thread pools through Executors, namely:
New CachedThreadPool creates a cacheable thread pool, which can flexibly reclaim idle threads if the length of the thread pool exceeds the processing requirements, and if not, create new threads.
New Fixed ThreadPool creates a fixed-length thread pool that controls the maximum number of concurrent threads, and the threads that exceed it will be
Wait in line. New Scheduled ThreadPool creates a fixed-length thread pool that supports timing and periodic task execution
. New Single ThreadExecutor creates a single threaded thread pool, which only uses a single worker thread to perform tasks, ensuring that all tasks are executed in a specified order (FIFO, LIFO, priority).

 

(1)newCachedThreadPool
Create a cacheable thread pool. If the length of the thread pool exceeds the processing requirement, it can flexibly reclaim idle threads. If there is no reclaimable thread, the new thread sample code is as follows:

  1. Packing test;  
  2. import  java.util.concurrent.ExecutorService;  
  3. import  java.util.concurrent.Executors;  
  4. publicclass 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.    attempt {  
  10.     Thread.sleep(index *  1000 );  
  11.    }  catch  (InterruptedException e){  
  12.     e.printStackTrace();  
  13.    }  
  14.    cachedThreadPool.execute(new  Runnable(){  
  15.     public void  run(){   
  16.      Of System.out.println(Index);  
  17.     }  
  18.    });  
  19.   }  
  20.  }  
  21. }  
Packaging test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
 public static void main(String [] args){
  ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
  for(int i = 0; i <10; i ++){
   final int index = i;
   //Attempt{
    Thread.sleep(index * 1000);
   } catch(InterruptedException e){
    e.printStackTrace();
   }
   cachedThreadPool.execute(new Runnable(){
    public void run(){
     //System.out.println (index);
    }
   });
  }
 }
}

 

The thread pool is infinite. When the first task is completed when the second task is executed, the threads that execute the first task are reused instead of creating new threads each time.
 
(2)newFixedThreadPool
Create a fixed-length thread pool. Controls the maximum number of concurrent threads, and the threads that exceed the maximum number of concurrent threads will wait in the queue for the sample code as follows:

  1. Packing test;  
  2. import  java.util.concurrent.ExecutorService;  
  3. import  java.util.concurrent.Executors;  
  4. publicclass 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.      attempt {  
  12.       Of System.out.println(Index);  
  13.       Thread.sleep(2000 );  
  14.      }  catch  (InterruptedException e){  
  15.       e.printStackTrace();  
  16.      }  
  17.     }  
  18.    });  
  19.   }  
  20.  }  
  21. }  
Packaging test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
 public static void main(String [] args){
  ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
  for(int i = 0; i <10; i ++){
   final int index = i;
   fixedThreadPool.execute(new Runnable() {
    public void run() {
     try {
      System.out.println(index);
      Thread.sleep(2000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   });
  }
 }
}

 
Because the size of the thread pool is 3 and each task sleeps 2 seconds after exporting the index, three numbers are typed every two seconds.
The size of a fixed-length thread pool is best set according to system resources, such as Runtime.getRuntime (). Available Processors ()

 

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

  1. Packing test;  
  2. import  java.util.concurrent.Executors;  
  3. import  java.util.concurrent.ScheduledExecutorService;  
  4. import  java.util.concurrent.TimeUnit;  
  5. publicclass 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. }  
package test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorTest {
 public static void main(String[] args) {
  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
  scheduledThreadPool.schedule(new Runnable() {
   public void run() {
    System.out.println("delay 3 seconds");
   }
  }, 3, TimeUnit.SECONDS);
 }
}

 
Represents a delay of 3 seconds.

The sample code is executed periodically as follows:

  1. Packing test;  
  2. import  java.util.concurrent.Executors;  
  3. import  java.util.concurrent.ScheduledExecutorService;  
  4. import  java.util.concurrent.TimeUnit;  
  5. publicclass 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 second, every 3 secondsExcludeOnce" );  
  11.    }  
  12.   },  1 ,  3 ,TimeUnit.SECONDS);  
  13.  }  
  14. }  
package test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorTest {
 public static void main(String[] args) {
  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
  scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
   public void run() {
    System.out.println("delay 1 seconds, and excute every 3 seconds");
   }
  }, 1, 3, TimeUnit.SECONDS);
 }
}

 
Represents execution every 3 seconds after a delay of 1 second.

 

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

  1. Packing test;  
  2. import  java.util.concurrent.ExecutorService;  
  3. import  java.util.concurrent.Executors;  
  4. publicclass 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.      attempt {  
  12.       Of System.out.println(Index);  
  13.       Thread.sleep(2000 );  
  14.      }  catch  (InterruptedException e){  
  15.       e.printStackTrace();  
  16.      }  
  17.     }  
  18.    });  
  19.   }  
  20.  }  
  21. }  
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
 public static void main(String[] args) {
  ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
  for (int i = 0; i < 10; i++) {
   final int index = i;
   singleThreadExecutor.execute(new Runnable() {
    public void run() {
     try {
      System.out.println(index);
      Thread.sleep(2000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   });
  }
 }
}

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

You can use JDK's own monitoring tools to monitor the number of threads we create, run an uninterrupted thread, and create a specified number of threads to observe:
Tools directory: C: Program Files Java jdk1.6.0_06 bin jconsole.exe
Modify the program slightly:

  1. Packing test;  
  2. import  java.util.concurrent.ExecutorService;  
  3. import  java.util.concurrent.Executors;  
  4. publicclass 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.      attempt {  
  12.       while (true ){  
  13.        Of System.out.println(Index);  
  14.        Thread.sleep(10  *  1000 );  
  15.       }  
  16.      }  catch  (InterruptedException e){  
  17.       e.printStackTrace();  
  18.      }  
  19.     }  
  20.    });  
  21.    attempt {  
  22.     Thread.sleep(500 );  
  23.    }  catch  (InterruptedException e){  
  24.     e.printStackTrace();  
  25.    }  
  26.   }  
  27.  }  
  28. }  
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
 public static void main(String[] args) {
  ExecutorService singleThreadExecutor = Executors.newCachedThreadPool();
  for (int i = 0; i < 100; i++) {
   final int index = i;
   singleThreadExecutor.execute(new Runnable() {
    public void run() {
     try {
      while(true) {
       System.out.println(index);
       Thread.sleep(10 * 1000);
      }
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   });
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}

 
The results are as follows:

 

Choose the program we run:

Monitor operation status

 

 

Please go to ITEYE website to see the original java Xiaoqiang, thank you!

http://cuisuqiang.iteye.com/ !

Build your own blog address: http : //www.javacui.com/ Content is synchronized with ITEYE!

Topics: Java JDK