Java線程池的設計與分析

1.線程池的好處

合理利用線程池可以帶來三個好處:緩存

  • 下降資源消耗併發

  • 提升響應速度ide

  • 提升線程的可管理性spa

2.線程池的使用

咱們能夠經過ThreadPoolExecutor來建立一個線程池:線程

new  ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, milliseconds,runnableTaskQueue, handler);

建立一個線程池須要輸入幾個參數:code

  • corePoolSize - 線程池的基本大小隊列

  • maximumPoolSize -線程池最大大小資源

  • keepAliveTime - 線程活動保持時間get

  • runableTaskQueue - 任務隊列it

 

3.線程池工做原理

 

經過線程池的處理流程以下:

1.首先線程池判斷基本線程池是否已滿?沒滿,建立一個工做線程來執行任務。滿了,則進入下個流程

2.其次線程池判斷工做隊列是否已滿?沒滿,則將新提交的任務存儲在工做隊列裏。滿了,則進入下個流程

3.最後線程池判斷整個線程池是否已滿? 沒滿, 則建立一個新的工做線程來執行任務, 滿了則交給飽和策略來處理任務

 

4.線程池的四種實現

Java經過Executors提供了四種線程池:

  • newCachedThreadPool 建立一個可緩存的線程池, 若是線程池長度超過處理須要,可靈活回收空閒線程,若無可回收,則新建線程

      newCacheThreadPool源代碼分析以下:

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

 

   實現的是SynchronousQueue

  • newFixThreadPool: 建立一個定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待

    newFixThreadPool源代碼:

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

 

  • newScheduledTheadPool:建立一個定長線程池, 支持定時及週期任務執行

    newScheduledThreadPool源代碼分析:

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}
  • newSingleThreadPool:建立一個單線程化的線程池

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

 

項目中使用

public class ThreadPoolTest {

    static class ExecutePrint implements Task {

        @Override
        public String getName() {
            return "threadpool";
        }

        @Override
        public void shutdown() {

        }

        @Override
        public void run() {
            System.out.println("hello world");

        }
    }

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(5000), new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolExecutor.submit(new ExecutePrint());
    }
}
public class ThreadPoolTest2 {

    public static void main(String[] args) {
       // ExecutorService executorService = Executors.newCachedThreadPool();
        //ExecutorService executorService = Executors.newFixedThreadPool(10);
        //ExecutorService executorService = Executors.newScheduledThreadPool(10);
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for(int i =0; i <10;i++){
            final int index = i;
            try {
                Thread.sleep(index*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(index);
                }
            });
        }
    }
}
相關文章
相關標籤/搜索