Home  >  Article  >  Java  >  Introduce the working characteristics of thread pool in Java with examples

Introduce the working characteristics of thread pool in Java with examples

高洛峰
高洛峰Original
2017-02-07 15:01:101470browse

Why do we have to use thread pool?

Personally I think the main reason is: there are a lot of tasks that need to be processed in a short period of time

The benefits of using a thread pool:

1. Reduce the time spent on creating and destroying threads Time and system resource overhead
2. If the thread pool is not used, it may cause the system to create a large number of threads and consume all the system memory

The following are several thread pools that come with Java:

1. newFixedThreadPool creates a thread pool with a specified number of worker threads.

Every time a task is submitted, a worker thread is created. If the number of worker threads reaches the initial maximum number of the thread pool, the submitted task is stored in the pool queue.

2. newCachedThreadPool creates a cacheable thread pool.

The characteristics of this type of thread pool are:

1). There is almost no limit on the number of worker threads created (in fact, there is a limit, the number is Interger. MAX_VALUE), so that it can be flexibly Add threads to the thread pool.

2). If no task is submitted to the thread pool for a long time, that is, if the worker thread is idle for the specified time (default is 1 minute), the worker thread will automatically terminate. After termination, if you submit a new task, the thread pool will recreate a worker thread.

3. newSingleThreadExecutor creates a single-threaded Executor, that is, only creates a unique worker thread to perform tasks. If this thread ends abnormally, another one will replace it to ensure sequential execution (I think this is its characteristic).

The biggest feature of a single worker thread is that it can guarantee the sequential execution of various tasks, and no multiple threads will be active at any given time.

4. newScheduleThreadPool creates a fixed-length thread pool and supports scheduled and periodic task execution, similar to Timer.

Summary:

1. FixedThreadPool is a typical and excellent thread pool. It has the advantages of a thread pool improving program efficiency and saving the overhead when creating threads. But when the thread pool is idle, that is, when there are no runnable tasks in the thread pool, it will not release the worker threads and will also occupy certain system resources.

two. The characteristic of CachedThreadPool is that when the thread pool is idle, that is, when there are no runnable tasks in the thread pool, it will release the worker thread, thereby releasing the resources occupied by the worker thread. However, when a new task appears, a new worker thread must be created, which requires a certain amount of system overhead. Moreover, when using CachedThreadPool, you must pay attention to controlling the number of tasks. Otherwise, due to a large number of threads running at the same time, the system may be paralyzed.

Java Thread Pool ThreadPoolExecutor Usage Example

package com.sondon.mayi.jpool; 
  
import java.util.concurrent.ArrayBlockingQueue; 
import java.util.concurrent.Callable; 
import java.util.concurrent.ExecutionException; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.ThreadPoolExecutor; 
import java.util.concurrent.TimeUnit; 
  
public class JPoolLearn { 
  
 private static int produceTaskSleepTime = 3; 
 private static int produceTaskMaxNumber = 20; 
   
 public void testThreadPoolExecutor(){ 
  /* 
   * ThreadPoolExecutor( 
   * int corePoolSize, //线程池维护线程的最少数量 
   * int maximumPoolSize, //线程池维护线程的最大数量 
   * long keepAliveTime, //线程池维护线程所允许的空闲时间 
   * TimeUnit unit, //线程池维护线程所允许的空闲时间的单位 
   * BlockingQueue<Runnable> workQueue, //线程池所使用的缓冲队列 
   * RejectedExecutionHandler handler //线程池对拒绝任务的处理策略 ) 
   */ 
  ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 
    5, 
    10, 
    3, 
    TimeUnit.SECONDS, 
    new ArrayBlockingQueue<Runnable>(10), 
    new ThreadPoolExecutor.DiscardOldestPolicy() 
    ); 
  
  for (int i = 1; i <= produceTaskMaxNumber; i++) { 
   try { 
    // 产生一个任务,并将其加入到线程池 
    String task = "task---" + i; 
    threadPool.execute(new ThreadPoolTask(task)); 
    System.out.println("activeCount :"+ threadPool.getActiveCount()); 
    // 便于观察,等待一段时间 
    Thread.sleep(produceTaskSleepTime); 
   } catch (Exception e) { 
    e.printStackTrace(); 
   } 
  } 
    
  //查看当前的线程池状况 
  while(true){ 
   try { 
    Thread.sleep(3000); 
    System.out.println("pool size :"+threadPool.getPoolSize());//线程池中线程数量 
    System.out.println("active count :"+threadPool.getActiveCount());//线程池中活动的线程数量 
   } catch (InterruptedException e) { 
    e.printStackTrace(); 
   } 
  } 
 } 
  
 /** 
  * 
  * @Author 蔡文锋 
  * @Data_Time 2015年7月25日 下午4:06:28 
  * @Description { 测试不同线程池模式 } 
  */ 
 public void testNewCachedThreadPool(){ 
  ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newCachedThreadPool(); 
//  ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newFixedThreadPool(100); 
//  ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newScheduledThreadPool(100); 
//  ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newSingleThreadExecutor(); 
  try { 
  for (int i = 0; i < 100; i++) { 
   // 产生一个任务,并将其加入到线程池 
   String task = "task---" + i; 
   threadPool.execute(new ThreadPoolTask(task)); 
   System.out.println("activeCount :"); 
   // 便于观察,等待一段时间 
   Thread.sleep(produceTaskSleepTime); 
     
   } 
  } catch (InterruptedException e) { 
   e.printStackTrace(); 
  } 
  //查看当前的线程池状况 
  while(true){ 
   try { 
    Thread.sleep(3000); 
    System.out.println("pool size :"+threadPool.getPoolSize());//线程池中线程数量 
    System.out.println("active count :"+threadPool.getActiveCount());//线程池中活动的线程数量 
   } catch (InterruptedException e) { 
    e.printStackTrace(); 
   } 
  } 
 } 
   
 /** 
  * 
  * @Author 蔡文锋 
  * @Data_Time 2015年7月25日 下午4:06:58 
  * @Description { 测试callable与runable方法的区别 } 
  */ 
 public void testNewCachedThreadPool_callable(){ 
  ExecutorService es=Executors.newFixedThreadPool(10); 
  try { 
     
//   String result=es.submit(new MyCallable<String>()).get(); 
//   System.out.println("callable result :"+result); 
     
   String result=(String) es.submit(new ThreadPoolTask("")).get(); 
   System.out.println("runable result :"+result); 
     
  } catch (InterruptedException | ExecutionException e) { 
   e.printStackTrace(); 
  } 
 } 
   
   
 public static void main(String[] args) { 
  new JPoolLearn().testNewCachedThreadPool(); 
 } 
} 
  
  
  
/** 
 * 线程池执行的任务 
 */ 
class ThreadPoolTask implements Runnable { 
 private static int consumeTaskSleepTime = 2000; 
 // 保存任务所需要的数据 
 private Object threadPoolTaskData; 
  
 ThreadPoolTask(Object tasks) { 
  this.threadPoolTaskData = tasks; 
 } 
  
 public void run() { 
  System.out.println("start .." + threadPoolTaskData); 
  try { 
   // Sleep 2秒 模拟耗时操作 
   Thread.sleep(consumeTaskSleepTime); 
  } catch (Exception e) { 
   e.printStackTrace(); 
  } 
  threadPoolTaskData = null; 
 } 
  
 public Object getTask() { 
  return this.threadPoolTaskData; 
 } 
} 
  
/** 
 * 
 * @Project : JPool 
 * @Package : com.sondon.mayi.jpool 
 * @Class : MyCallable 
 * @param <T> 
 */
class MyCallable<T> implements Callable<T>{ 
   
 @Override
 public T call() throws Exception { 
   System.out.println("开始执行Callable"); 
   return (T) "测试callable接口"; 
  } 
}

For more examples to introduce the working characteristics of the thread pool in Java, please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn