最近寫了一個(gè)并發(fā)冪等測(cè)試,用線程池加入多個(gè)線程,同時(shí)啟動(dòng),領(lǐng)導(dǎo)覺得這樣有一定的風(fēng)險(xiǎn),要求更嚴(yán)格一點(diǎn),把所有的線程加入池中,然后同時(shí)啟動(dòng)。
本來有多種方法,因?yàn)槲覀冃枰獜亩鄠€(gè)線程中獲取返回值,所以我們用CountDownLatch來同步多線程。CyclicBarrier也是可以同步多線程的,但因?yàn)槠錈o法獲取返回值,最后只能選擇CountDownLatch.
因公司的代碼不便共享,這里只提供一小部分代碼。
CountDownLatch latch = new CountDownLatch(1);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<br data-filtered= "filtered" >ExecutorService pool; if (concurrentNum != null &&concurrentNum <= maxConcurrentNum && concurrentNum > 0 ) { pool = Executors.newFixedThreadPool(concurrentNum); } else { concurrentNum = defaultConcurrentNum; pool = Executors.newFixedThreadPool(defaultConcurrentNum); } for ( int i = 0 ; i < concurrentNum; i++) { Future res = pool.submit( new Callable<Object>() { @Override public Object call() throws Exception { latch.await(); Object retObj = executeApi(); return retObj; } }); resultList.add(res); } latch.countDown(); for ( int i = 0 ; i < concurrentNum; i++) { retList.add(resultList.get(i).get()); } pool.shutdown(); |
這里順便提一下,latch在中文中就是門栓的意思,這樣就很好理解了,當(dāng)有門栓時(shí),latch.await()的線程都在等待,只有當(dāng)門栓的個(gè)數(shù)為0時(shí)那些線程才能同時(shí)釋放出來,所以能同步運(yùn)行多線程。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/linwenbin/p/12700983.html