ExecutorService接口是java內(nèi)置的線程池接口,通過(guò)學(xué)習(xí)接口中的方法,可以快速的掌握java內(nèi)置線程池的基本使用常用方法:
- void shutdown():?jiǎn)?dòng)一次順序關(guān)閉披诗,執(zhí)行以前提交的任務(wù),但不接受新任務(wù)。
- List<Runnable> shutdownNow():停止所有正在執(zhí)行的任務(wù)汤功,暫停處理正在等待的任務(wù)黎侈,并返回等待執(zhí)行的任務(wù)列表荤懂。<T> Future<T> submit(Callable<T> task)執(zhí)行帶返回值的任務(wù)燎潮,返回一個(gè)Future對(duì)象蔑滓。
- <T> Future<?> submit(Runnable task):執(zhí)行Runnable任務(wù)灰嫉,并返回一個(gè)表示該任務(wù)的Future拆宛。
- Future<T> submit(Runnable task, T result)執(zhí)行Runnable 任務(wù),并返回一個(gè)表示該任務(wù)的Future讼撒。
一浑厚、內(nèi)置線程池
- 獲取ExecutorService可以利用JDK中的Executors類中的靜態(tài)方法,常用獲取方式如下:
- static ExecutorService newCachedThreadPool():創(chuàng)建一個(gè)默認(rèn)的線程池對(duì)象,里面的線程可重用,且在第一次使用時(shí)才創(chuàng)建;
- static ExecutorService newCachedThreadPool(ThreadFactory threadFactory):
線程池中的所有線程都使用ThreadFactory來(lái)創(chuàng)建,這樣的線程無(wú)需手動(dòng)啟動(dòng),自動(dòng)執(zhí)行根盒;
- static ExecutorService newFixedThreadPool(int nThreads):創(chuàng)建一個(gè)可重用固定線程數(shù)的線程池
- static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory:創(chuàng)建一個(gè)可重用固定線程數(shù)的線程池且線程池中的所有線程都使用ThreadFactory來(lái)創(chuàng)建钳幅;
- static ExecutorService newSingleThreadExecutor():創(chuàng)建一個(gè)使用單個(gè)worker線程的Executor,以無(wú)界隊(duì)列方式來(lái)運(yùn)行該線程郑象;
- static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory):創(chuàng)建一個(gè)使用單個(gè)worker線程的Executor贡这,且線程池中的所有線程都使用ThreadFactory來(lái)創(chuàng)建;
- ScheduledExecutorService是ExecutorService的子接口,具備了延遲運(yùn)行或定期執(zhí)行任務(wù)的能力,常用獲取方式如下:
- static ScheduledExecutorService newScheduledThreadPool(int corePoolSize):創(chuàng)建一個(gè)可重用固定線程數(shù)的線程池且允許延遲運(yùn)行或定期執(zhí)行任務(wù);
- static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory):創(chuàng)建一個(gè)可重用固定線程數(shù)的線程池且線程池中的所有線程都使用ThreadFactory來(lái)創(chuàng)建,且允許延遲運(yùn)行或定期執(zhí)行任務(wù);
- static ScheduledExecutorService newSingleThreadScheduledExecutor():
創(chuàng)建一個(gè)單線程執(zhí)行程序厂榛,它允許在給定延遲后運(yùn)行命令或者定期地執(zhí)行盖矫。- static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory):
創(chuàng)建一個(gè)單線程執(zhí)行程序,它可安排在給定延遲后運(yùn)行命令或者定期地執(zhí)行击奶。
- ScheduledExecutorService常用方法如下:
- <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit):延遲時(shí)間單位是unit,數(shù)量是delay的時(shí)間后執(zhí)行callable辈双。
- ScheduledFuture<?> schedule(Runnable command, long delay,TimeUnit unit):延遲時(shí)間單位是unit,數(shù)量是delay的時(shí)間后執(zhí)行command。
- ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit):延遲時(shí)間單位是unit,數(shù)量是initialDelay的時(shí)間后,每間隔period時(shí)間重復(fù)執(zhí)行一次command柜砾。
- ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delayTimeUnit unit):創(chuàng)建并執(zhí)行一個(gè)在給定初始延遲后首次啟用的定期操作湃望,隨后,在每一次執(zhí)行終止和下一次執(zhí)行開(kāi)始之間都存在給定的延遲痰驱。