java併發編程學習之線程池-預約義線程池(四)

系統預約了幾個線程池,不過建議手動建立,以防止錯誤建立消耗資源,好比建立太多線程或者OOM多線程

FixedThreadPool

建立一個固定長度的線程池,每提交一個任務時就建立一個線程,知道達到線程池的最大數量。無界隊列ide

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

SingleThreadExecutor

單線程的Executor,固定線程數量,數量爲1,無界隊列,會按順序執行spa

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

CachedThreadPool

不限制線程數量,使用SynchronousQueue隊列,使用於短任務。任務增長時,建立新的線程,線程的數量不受限制。線程池的規模超過當前的處理請求,回收空閒的線程。線程

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

WorkStealingPool

基於ForkJoinPoolcode

public static ExecutorService newWorkStealingPool(int parallelism) {
    return new ForkJoinPool
        (parallelism,
         ForkJoinPool.defaultForkJoinWorkerThreadFactory,
         null, true);
}

ScheduledThreadPoolExecutor

用於週期性執行任務orm

public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
    return new DelegatedScheduledExecutorService
        (new ScheduledThreadPoolExecutor(1));
}

示例

public class ScheduledDemo {
    static class Thread1 implements Runnable {
        @Override
        public void run() {
            SimpleDateFormat formater = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            System.out.println(Thread.currentThread().getName() + ":" + formater.format(new Date()));
        }
    }

    public static void main(String[] args) {
        ScheduledThreadPoolExecutor schedule
                = new ScheduledThreadPoolExecutor(1);
        //第一個是Runnable,第二個是第一次開始的時間,第三個是週期時間,第四個是時間單位
        schedule.scheduleAtFixedRate(new Thread1(),1000,1000, TimeUnit.MILLISECONDS);
    }
}

運行結果以下:blog

clipboard.png

相關文章
相關標籤/搜索