Four common thread pools in java

Keywords: Programming Java

1.newCachedThreadPool

Create a cacheable thread pool. If the thread length exceeds the processing requirement, it can flexibly reclaim idle threads. If there is no reclaimable thread, it can create new threads.

The characteristics of this thread pool are:

  1. There is almost no limit to the number of worker threads created (the maximum number of Interger.MAX_VALUE), so that threads can be added to the thread pool flexibly.
  2. If the task is not submitted to the thread pool for a long time, that is, if the worker thread is idle for a specified time (default 1 minute), the worker thread will automatically terminate. After termination, if you submit a new task, the thread pool recreates a worker thread.
  3. When using CachedThreadPool, we must pay attention to controlling the number of tasks, otherwise, because a large number of threads run at the same time, it is likely to cause system paralysis.
 package 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;
    try {
     Thread.sleep(index * 1000);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    cachedThreadPool.execute(new Runnable() {
     public void run() {
      System.out.println(index);
     }
    });
   }
  }
 }

 

5.2 newFixedThreadPool

Create a thread pool that specifies the number of worker threads. Every time a task is submitted, a worker thread is created. If the number of worker threads reaches the maximum of the initial number of thread pools, the submitted tasks are stored in the pool queue.

Fixed ThreadPool is a typical and excellent thread pool, which has the advantages of improving program efficiency and saving the cost of creating threads. However, when the thread pool is idle, that is, when there are no runnable tasks in the thread pool, it will not release the working threads, but also occupy certain system resources.

The sample code is as follows:

 

 

package 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 thread pool size is 3 and each task has two seconds sleep after index output, three digits are printed every two seconds.
The size of a fixed-length thread pool is best set according to system resources, such as Runtime.getRuntime().availableProcessors().

 

5.3 newSingleThreadExecutor

Create a single-threaded Executor, that is, only create a single worker thread to perform tasks. It only uses a single worker thread to perform tasks, ensuring that all tasks are executed in a specified order (FIFO, LIFO, priority). If this thread ends abnormally, another thread will replace it to ensure sequential execution. The greatest feature of a single worker thread is that it guarantees that tasks are executed sequentially and that no more threads are active at any given time.

The sample code is as follows:

 

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();
     }
    }
   });
  }
 }
} 

 

 

5.4 newScheduleThreadPool

Create a fixed-length thread pool, and support timing and periodic task execution, support timing and periodic task execution.

Delay execution by 3 seconds. Delay execution sample code as follows:

 

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 execution every 3 seconds after a delay of 1 second, and executes the sample code periodically as follows:

 

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);
 }
}

 

Posted by toasty2 on Sat, 19 Jan 2019 22:42:12 -0800