執行緒池以及四種常見執行緒池

bok發表於2018-08-07

執行緒池以及四種常見執行緒池

public ThreadPoolExecutor(int corePoolSize,//核心執行緒池大小,核心執行緒將會盡可能地一直活著
                          int maximumPoolSize,//執行緒池最大數量包括核心執行緒數量
                          long keepAliveTime,//非核心執行緒最長存活時間
                          TimeUnit unit,//keepAliveTime的單位
                          BlockingQueue<Runnable> workQueue,//等待執行緒的佇列
                          ThreadFactory threadFactory,//執行緒工程
                          RejectedExecutionHandler handler)//執行緒拒絕執行回撥
複製程式碼

四種常見的執行緒池:

  • Executors.newCachedThreadPool()

    new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>())
    複製程式碼
  • Executors.newFixedThreadPool(int nThreads)

    new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>())
    複製程式碼
  • Executors.newScheduledThreadPool(int nCorepoolSize)

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    
    //ScheduledThreadPoolExecutor():
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE,
              DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
              new DelayedWorkQueue());
    }
    複製程式碼

  • Executors.newSingleThreadPool()

    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
    複製程式碼

相關文章