JAVA線程池使用

線程池的建立

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("xxx-thread-%d").build();

ExecutorService executor = new ThreadPoolExecutor(16, 
                                                  32, 
                                                  60000L, 
                                                  TimeUnit.SECONDS, 
                                                  new LinkedBlockingQueue<Runnable>(200), 
                                                  namedThreadFactory, 
                                                  new DiscardOldestPolicy());
複製代碼

ThreadPoolExecutor構造函數說明

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) {
            throw new IllegalArgumentException();
        }
        if (workQueue == null || threadFactory == null || handler == null){
            throw new NullPointerException();
        }
        this.acc = System.getSecurityManager() == null ? null : AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
複製代碼

corePoolSize

保持在池中的線程數,即便它們是空閒的; 設置{@code allowCoreThreadTimeOut},容許線程數低於corePoolSize時,線程也由於空閒而終止。java

maximumPoolSize

池中容許的最大線程數bash

keepAliveTime

當線程數大於corePoolSize時,多餘的空閒線程等待新任務的最大時間,超過此時間會被回收。ide

unit

keepAliveTime的時間單位函數

workQueue

用於在任務執行前保存任務的隊列。這個隊列將只包含{@code execute}方法提交的{@code Runnable}任務。ui

threadFactory

執行程序建立新線程時使用的線程工廠this

handler

RejectedExecutionHandler(飽和策略):當隊列和線程池都滿了,說明線程池處於飽和狀態,那麼必須採起一種策略處理提交的新任務。spa

四種默認的飽和策略

AbortPolicy

默認的飽和策略,直接拋出java.util.concurrent.RejectedExecutionException異常
複製代碼

CallerRunsPolicy

任務被拒絕添加後,會調用當前線程池的所在的線程去執行被拒絕的任務。這個策略的缺陷就是可能會阻塞主線程。
複製代碼

DiscardPolicy

讓被線程池拒絕的任務直接拋棄,不會拋異常也不會執行。
複製代碼

DiscardOldestPolicy

當任務被拒絕添加時,會拋棄任務隊列中最早加入隊列的,再把這個新任務添加進去。
複製代碼

自定義飽和策略

  • 實現java.util.concurrent.RejectedExecutionHandler接口
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 
 * @version 1.0.0
 * @Description  捨棄隊列中最早加入的五條任務,並將新的任務加入隊尾
 * @date 2020/6/2 21:25
 * @since 1.8
 */
public class MyRejectedPolicy implements RejectedExecutionHandler {

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        if (!executor.isShutdown()){
            executor.getQueue().poll();
            executor.getQueue().poll();
            executor.getQueue().poll();
            executor.getQueue().poll();
            executor.getQueue().poll();
            executor.getQueue().offer(r);
        }
    }
}
複製代碼
相關文章
相關標籤/搜索