亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java多線程ThreadPoolExecutor詳解

 更新時(shí)間:2022年08月12日 14:45:12   作者:七國(guó)的天下,我要九十九  
這篇文章主要介紹了Java多線程ThreadPoolExecutor詳解,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下

前言:

根據(jù)ThreadPoolExecutor的構(gòu)造方法,JDK提供了很多工廠方法來(lái)創(chuàng)建各種用途的線程池.

1 newFixedThreadPool

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

說(shuō)明:

  • 核心線程數(shù) == 最大線程數(shù)(沒(méi)有救急線程被創(chuàng)建),因此也無(wú)需超時(shí)時(shí)間
  • 阻塞隊(duì)列是無(wú)界的,可以放任意數(shù)量的任務(wù)(最大為Integer.MAX_VALUE)

適用于 任務(wù)量一已知,相對(duì)耗時(shí)的任務(wù)

2 newCachedThreadPool

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

說(shuō)明:

  • 核心線程數(shù)是 0, 最大線程數(shù)是 Integer.MAX_VALUE,救急線程的空閑生存時(shí)間是 60s
    • 全部都是救急線程(60s 后可以回收)
    • 救急線程可以無(wú)限創(chuàng)建(最大是Integer.MAX_VALUE)
  • 隊(duì)列采用了 SynchronousQueue 實(shí)現(xiàn)特點(diǎn)是,它沒(méi)有容量,沒(méi)有線程來(lái)取是放不進(jìn)去的(一手交錢、一手交 貨)

如下案例:

SynchronousQueue<Integer> integers = new SynchronousQueue<>();
new Thread(() -> {
     try {
         log.debug("putting {} ", 1);
         integers.put(1);
         log.debug("{} putted...", 1);
         log.debug("putting...{} ", 2);
         integers.put(2);
         log.debug("{} putted...", 2);
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
},"t1").start();
sleep(1);
new Thread(() -> {
     try {
         log.debug("taking {}", 1);
         integers.take();
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
},"t2").start();
sleep(1);
new Thread(() -> {
     try {
         log.debug("taking {}", 2);
         integers.take();
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
},"t3").start();
/*
運(yùn)行結(jié)果:
11:48:15.500 c.TestSynchronousQueue [t1] - putting 1 
11:48:16.500 c.TestSynchronousQueue [t2] - taking 1 
11:48:16.500 c.TestSynchronousQueue [t1] - 1 putted... 
11:48:16.500 c.TestSynchronousQueue [t1] - putting...2 
11:48:17.502 c.TestSynchronousQueue [t3] - taking 2 
11:48:17.503 c.TestSynchronousQueue [t1] - 2 putted... 
*/

整個(gè)線程池表現(xiàn)為線程數(shù)會(huì)根據(jù)任務(wù)量不斷增長(zhǎng),沒(méi)有上限,當(dāng)任務(wù)執(zhí)行完畢,空閑 1分鐘后釋放線程。

適用于 任務(wù)數(shù)比較密集,但每個(gè)任務(wù)執(zhí)行時(shí)間較短的情況

3 newSingleThreadExecutor

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

希望多個(gè)任務(wù)排隊(duì)執(zhí)行。線程數(shù)固定為 1,任務(wù)數(shù)多于 1 時(shí),會(huì)放入無(wú)界隊(duì)列排隊(duì)。任務(wù)執(zhí)行完畢,這唯一的線程也不會(huì)被釋放.

與其他線程區(qū)別:

  • 自己創(chuàng)建一個(gè)單線程串行執(zhí)行任務(wù),如果任務(wù)執(zhí)行失敗而終止那么沒(méi)有任何補(bǔ)救措施,而線程池還會(huì)新建一 個(gè)線程,保證池的正常工作
  • Executors.newSingleThreadExecutor() 線程個(gè)數(shù)始終為1,不能修改
    • FinalizableDelegatedExecutorService 應(yīng)用的是裝飾器模式,只對(duì)外暴露了 ExecutorService 接口,因此不能調(diào)用 ThreadPoolExecutor 中特有的方法.
  • Executors.newFixedThreadPool(1) 初始時(shí)為1,以后還可以修改
    • 對(duì)外暴露的是 ThreadPoolExecutor 對(duì)象,可以強(qiáng)轉(zhuǎn)后調(diào)用 setCorePoolSize 等方法進(jìn)行修改

4 提交任務(wù)

// 執(zhí)行任務(wù)
void execute(Runnable command);
// 提交任務(wù) task,用返回值 Future 獲得任務(wù)執(zhí)行結(jié)果
<T> Future<T> submit(Callable<T> task);
// 提交 tasks 中所有任務(wù)
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
 throws InterruptedException;
// 提交 tasks 中所有任務(wù),帶超時(shí)時(shí)間
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
 long timeout, TimeUnit unit)
 throws InterruptedException;
// 提交 tasks 中所有任務(wù),哪個(gè)任務(wù)先成功執(zhí)行完畢,返回此任務(wù)執(zhí)行結(jié)果,其它任務(wù)取消
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
 throws InterruptedException, ExecutionException;

// 提交 tasks 中所有任務(wù),哪個(gè)任務(wù)先成功執(zhí)行完畢,返回此任務(wù)執(zhí)行結(jié)果,其它任務(wù)取消,帶超時(shí)時(shí)間
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
 long timeout, TimeUnit unit)
 throws InterruptedException, ExecutionException, TimeoutException;

上述都是提供的提交任務(wù)的方法,根據(jù)不同的業(yè)務(wù)場(chǎng)景需求,選擇對(duì)應(yīng)的提交方法.

5 關(guān)閉線程池

shutdown

/*
線程池狀態(tài)變?yōu)?SHUTDOWN
- 不會(huì)接收新任務(wù)
- 但已提交任務(wù)會(huì)執(zhí)行完
- 此方法不會(huì)阻塞調(diào)用線程的執(zhí)行
*/
void shutdown();
public void shutdown() {
     final ReentrantLock mainLock = this.mainLock;
     mainLock.lock();
     try {
     checkShutdownAccess();
     // 修改線程池狀態(tài)
     advanceRunState(SHUTDOWN);
     // 僅會(huì)打斷空閑線程
     interruptIdleWorkers();
     onShutdown(); // 擴(kuò)展點(diǎn) ScheduledThreadPoolExecutor
     } finally {
     mainLock.unlock();
     }
     // 嘗試終結(jié)(沒(méi)有運(yùn)行的線程可以立刻終結(jié),如果還有運(yùn)行的線程也不會(huì)等)
     tryTerminate();
}

shutdownNow

/*
線程池狀態(tài)變?yōu)?STOP
- 不會(huì)接收新任務(wù)
- 會(huì)將隊(duì)列中的任務(wù)返回
- 并用 interrupt 的方式中斷正在執(zhí)行的任務(wù)
*/
List<Runnable> shutdownNow();
public List<Runnable> shutdownNow() {
     List<Runnable> tasks;
     final ReentrantLock mainLock = this.mainLock;
     mainLock.lock();
     try {
     checkShutdownAccess();
     // 修改線程池狀態(tài)
     advanceRunState(STOP);
     // 打斷所有線程
     interruptWorkers();
     // 獲取隊(duì)列中剩余任務(wù)
     tasks = drainQueue();
     } finally {
     mainLock.unlock();
     }
     // 嘗試終結(jié)
     tryTerminate();
     return tasks;
}

其他打斷方法

// 不在 RUNNING 狀態(tài)的線程池,此方法就返回 true
boolean isShutdown();
// 線程池狀態(tài)是否是 TERMINATED
boolean isTerminated();
// 調(diào)用 shutdown 后,由于調(diào)用線程并不會(huì)等待所有任務(wù)運(yùn)行結(jié)束,因此如果它想在線程池 TERMINATED 后做些事
情,可以利用此方法等待
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;

到此這篇關(guān)于Java多線程ThreadPoolExecutor詳解的文章就介紹到這了,更多相關(guān)Java ThreadPoolExecutor內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論