java線程池創建與調用

public class ExcutorUtil {

    static ExecutorService fixedThreadPool = null;
    //線程池大小,可自己定義
    static final Integer nThreads = 100;

    static {
        if (fixedThreadPool == null) {
            fixedThreadPool = new ThreadPoolExecutor(nThreads, nThreads,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>());
        }
    }

    public static void execute(Thread thread) {
        fixedThreadPool.execute(thread);
    }

    public static Future<?> submit(Callable<?> c) {
        return (Future<?>) fixedThreadPool.submit(c);
    }

    public static void execute(Runnable runnable) {
        fixedThreadPool.execute(runnable);
    }
}
  • 創建源碼爲:
 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
  •  參數解析
序號 名稱 類型 含義
1 corePoolSize int 核心線程池大小
2 maximumPoolSize int 最大線程池大小
3 keepAliveTime long 線程最大空閒時間
4 unit TimeUnit 時間單位
5 workQueue BlockingQueue<Runnable> 線程等待隊列
6 threadFactory ThreadFactory 線程創建工廠
7 handler RejectedExecutionHandler 拒絕策略

 

  • 以下代碼爲調用代碼
     ExcutorUtil.execute(()->{
            //do something
       });

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章