Executors浅析
2019獨角獸企業重金招聘Python工程師標準>>>
#簡述 Executors是一個工廠類,是ExecutorService的實用方法。他能夠產生ExecutorService、ScheduledExecutorService、ThreadFactory和Callable實例。 #方法介紹
public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}創建一個線程數固定的可復用線程池。該線程池包含一個無界共享隊列。線程池中有固定的活躍線城處理任務,如果多余的任務進入則放置到無界共享隊列中去等待有線程空余。如果有任何一個線程在線程池關閉之前執行任務的過程中失敗而被終止,則新的線程將要代替它執行子任務。線程池里面的線程在線程池被關閉之前一直存活。
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),threadFactory);}和上一個不同的是,構造方法新加了一個線程工廠。該工廠能夠在必要的時候為線程池新增線程。
public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));}static class FinalizableDelegatedExecutorServiceextends DelegatedExecutorService {FinalizableDelegatedExecutorService(ExecutorService executor) {super(executor);}protected void finalize() {super.shutdown();}}創建一個單線程的線程池。該方法返回了一個FinalizableDelegatedExecutorService實例,FinalizableDelegatedExecutorService類是ExecutorService的包裝類。
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),threadFactory));}也是一個單線程池,返回了包裝類,拒絕修改線程池信息,并且放置了一個線程工廠類,可以在適當的時候新生成一個線程(比如以前的那個線程由于異常狀況被關閉)。
public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}創建一個線程池,線程池中創建需要的線程。任務可以復用之前創建的線程。該線程池能夠通過執行許多生命周期段的異步任務來提高程序性能。在調用execute方法的過程中會復用之前創建的可用線程。如果沒有線程可用,線程池會新創建線程并添加到線程池中,如果線程超過60秒鐘還未使用則會從緩存中刪除。
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1));}創建了一個單線程執行周期性任務。返回包裝器類,不可改變線程池信息。
public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1, threadFactory));}和上面的方法類似,不同的是指定了創建新線程的工廠實例。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {return new ScheduledThreadPoolExecutor(corePoolSize);}創建執行周期任務的線程池,線程池中的線程數為corePoolSize。
轉載于:https://my.oschina.net/zjItLife/blog/668274
總結
以上是生活随笔為你收集整理的Executors浅析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓--selector简单使用
- 下一篇: Hadoop发行版的比较与选择