線程池好處:java
execute的邏輯:框架
線程池會將傳入的Runnable封裝成Worker,執行完後自動獲取阻塞隊列的下一個Runnable異步
線程池構造方法ui
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
線程池執行Runnable有兩個方法:execute(Runnable task)和submit(Runnable task)兩個方法,區別是submit會返回一個Feature對象,Feature對象能夠調用get()獲取返回值,會阻塞當前線程直到任務完成,同時提供了get(long timeout, TimeUnit unit)超時拋出TimeOutException脫離阻塞。線程
Executor框架主要由3大部分組成:rest
ThreadPoolExecutor一般使用工廠類Executors來建立,能夠建立3種類型的SingleThreadExecutor、FixedThreadPool、CachedThreadPoolcode
FixedThreadPool:orm
public static ExecutorService newFixedThreadPool(int nThreads){ return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
corePoolSize = maximumPoolSize, keepAliveTime = 0L, 使用無界LinkedBlockingQueue對象
SingleThreadExecutor:繼承
public static ExecutorService newSingleThreadPool(){ return new FinalizableDelegatedExecutorService( new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
CachedThreadPool:
public static ExecutorService newCachedThreadPool(){ return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }