Create a simple thread pool ThreadPoolTaskExecutor

1. Create

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);//核心线程大小
        executor.setMaxPoolSize(10);//最大线程大小
        executor.setQueueCapacity(100);//队列最大容量
        executor.setKeepAliveSeconds(3000);//存活时间
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//拒绝执行时如何处理

2. Use

executor.submit(new ThreadDemo());//或者executor.execute(new ThreadDemo());
// ----------------------------
public class ThreadDemo implements Runnable {
     @Override
     public void run() {
         //业务处理
     }
 }

Use to have ended here, here are some instructions

3. execution

3.1 If at this time the number of threads in the pool is less than corePoolSize, even if the threads in the pool are idle, but also create a new thread to handle the tasks are added.

3.2 If at this time is equal to the number of threads in the pool corePoolSize, but workQueue buffer queue is not full, the task is placed in the buffer queue.

3.3 if this time is greater than the number of threads in the pool corePoolSize, workQueue buffer queue is full, and the number of threads in the pool is less than the maxPoolSize, build a new thread to process the task is added.

4.4 if this time is greater than the number of threads in the pool corePoolSize, workQueue buffer queue is full, and the number of threads in the pool is equal to the maxPoolSize, then processed by the task handler specified policy. That is: the priority processing tasks are: core thread corePoolSize, task queue workQueue, maximum thread maximumPoolSize, if all three are full, use handler processing task rejected.

When the number of threads in the pool is greater than corePoolSize, if the idle time exceeds a thread keepAliveTime, the thread is terminated. In this way, the thread pool can dynamically adjust the number of threads in the pool.

4. Refuse processing

4.1 ThreadPoolExecutor.AbortPolicy: RejectedExecutionException discard task and throw an exception
4.2 ThreadPoolExecutor.DiscardPolicy: discard task, but do not throw an exception.
4.3 ThreadPoolExecutor.DiscardOldestPolicy: discard the head of the queue.
4.4 ThreadPoolExecutor.CallerRunsPolicy: handle the task by the caller.

5. submit and execute difference

  1. Received parameters are not the same
  2. submit returns a value, execute no return value
  3. submit exception handling (Future.get ())

Guess you like

Origin blog.csdn.net/weixin_34268579/article/details/90879474