Summary of java thread pool

The creation and efficiency of threads need to consume cpu resources, so we need to pay attention when using threads. Every action of you needs to pay for it. It is precisely because the use of threads needs to be cautious that java has also sealed the management of threads. That is to say, today's thread pool. At present, java mainly encapsulates about four types of threads Pool, let's introduce it briefly.

Four types of thread pools

  1. newCachedThreadPool creates a cacheable thread pool. If the length of the thread pool exceeds the processing requirements, idle threads can be recycled flexibly. If there is no recyclable thread, a new thread can be created.
  2. newFixedThreadPool creates a fixed length thread pool, which can control the maximum concurrent number of threads. The exceeded threads will wait in the queue.
  3. New scheduledthreadpool creates a fixed length thread pool that supports scheduled and periodic task execution.
  4. The new single thread executor creates a single threaded thread pool, which only uses unique worker threads to execute tasks and ensures that all tasks are executed in the specified order (FIFO, LIFO, priority).

Three main parameters in thread pool

corePoolSize:
The basic size of the thread pool, that is, the size of the thread pool when there is no task to execute, and only when the work queue is full can more threads be created. Note here: when the ThreadPoolExecutor is just created, the thread will not start immediately, but will not start until a task is submitted, unless the core thread is started in advance by calling prestartCoreThread/prestartAllCoreThreads. Considering the influence of keepAliveTime and allowCoreThreadTimeOut parameters, when there is no task to execute, the size of thread pool is not necessarily corePoolSize.
maximumPoolSize:
The maximum number of threads allowed in the thread pool that cannot be exceeded by the current number of threads in the thread pool. If the queue is full and the current number of threads is less than maximumPoolSize, a new thread is created to execute the task. It is worth mentioning here is largestPoolSize, which records the maximum number of threads in the whole life cycle of the thread pool. Why once? Because after the thread pool is created, setMaximumPoolSize() can be called to change the maximum number of threads running.
poolSize:
The current number of threads in the thread pool. When the value is 0, it means that there are no threads and the thread pool will terminate; at the same time, the poolSize will not exceed maximumPoolSize.

Related instance code

newCachedThreadPool cache pool

 /**
   * newCachedThreadPool The thread is automatically allocated and cannot control the upper limit
   */
  @Test
  public void newCachedThreadPool() {
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    for (int i = 0; i < 20; i++) {
      cachedThreadPool.execute(new Runnable() {
        @Override
        public void run() {
          logger.info("cachedThreadPool Test code:{}", Thread.currentThread().getName());
        }
      });
    }
  }

newFixedThreadPool controls the thread pool on-line

  /**
   * newFixedThreadPool Control the maximum number of threads, you can control the upper limit
   */
  @Test
  public void newFixedThreadPool() {
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 20; i++) {
      fixedThreadPool.execute(new Runnable() {
        @Override
        public void run() {
          logger.info("fixedThreadPool Test code:{}", Thread.currentThread().getName());
        }
      });
    }
  }

The newSingleThreadExecutor only has a thread pool of one thread. Only when a thread has an exception will a new thread be created to replace it

  /**
   * newSingleThreadExecutor There is only one thread. When this thread ends because of an exception, a new thread will replace it
   */
  @Test
  public void newSingleThreadExecutor() {
    ExecutorService newSingleThread = Executors.newSingleThreadExecutor();
    for (int i = 0; i < 20; i++) {
      newSingleThread.execute(new Runnable() {
        @Override
        public void run() {
          logger.info("newSingleThread Test code:{}", Thread.currentThread().getName());
        }
      });
    }
  }

New scheduledthreadpool a thread pool with scheduling function, which can perform periodic tasks

/**
   * newScheduledThreadPool Periodic tasks at intervals
   */
  @Test
  public void newScheduledThreadPool() throws InterruptedException {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
    executor.scheduleAtFixedRate(() -> {
      long start = new Date().getTime();
      System.out.println("scheduleAtFixedRate Start execution time:" +
          DateFormat.getTimeInstance().format(new Date()));
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      long end = new Date().getTime();
      System.out.println("scheduleAtFixedRate Execution takes time=" + (end - start) / 1000 + "m");
      System.out.println("scheduleAtFixedRate Execution completion time:" + DateFormat.getTimeInstance().format(new Date()));
      System.out.println("======================================");
    }, 0, 1, TimeUnit.SECONDS);//initialDelay initialization delay, period: minimum interval between two executions

    Thread.sleep(1000 * 10);
  }

Tags: Java less

Posted on Wed, 25 Mar 2020 21:44:23 -0400 by jroscoe