日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

一种父线程阻塞等待子线程的有效方法

發布時間:2023/11/30 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 一种父线程阻塞等待子线程的有效方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? ?最近在做一個查詢優化時,考慮到一次查詢耗時較多,所以打算用多線程來做,之前是串行查詢。比如一個用戶查詢觸發50個線程,在只有一個用戶的情況下,性能比串行查詢確實提高了許多,但當多個用戶同時觸發查詢的時候,CPU卻飆高得很厲害,比串行查詢好不了多少。

? ? ? ?因為一次查詢是同步查詢,即要等待所有的線程完成后才返回結果,所以一開始想到的辦法是每次查詢都起一個線程池,這個線程池里面有50個線程,這個線程池阻塞等待所有的線程完成然后返回結果,從而造成50個用戶同時查詢時起了50個線程池,cpu資源消耗殆盡。能不能做到所用用戶查詢觸發的線程統一由一個線程池控制呢?百度后終于找到了解決辦法。

1 import java.util.concurrent.CountDownLatch; 2 3 public class ThreadA implements Runnable { 4 5 private CountDownLatch cDownLatch; 6 7 private String name; 8 9 public ThreadA(CountDownLatch cDownLatch, String threadName) { 10 this.cDownLatch = cDownLatch; 11 this.name = threadName; 12 } 13 14 @Override 15 public void run() { 16 System.out.println(name + " begin."); 17 try { 18 Thread.sleep(500); 19 } catch (InterruptedException e) { 20 e.printStackTrace(); 21 } 22 System.out.println(name + " end."); 23 cDownLatch.countDown(); 24 } 25 } 線程執行體 1 import java.util.concurrent.BlockingQueue; 2 import java.util.concurrent.LinkedBlockingQueue; 3 import java.util.concurrent.ThreadPoolExecutor; 4 import java.util.concurrent.TimeUnit; 5 6 public class MyThreadPool extends ThreadPoolExecutor { 7 8 private static MyThreadPool myPool = new MyThreadPool(10, 100, 1, 9 TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>()); 10 11 private MyThreadPool(int corePoolSize, int maximumPoolSize, 12 long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { 13 super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); 14 } 15 16 public static MyThreadPool getInstance() { 17 return myPool; 18 } 19 } 線程池 import java.util.concurrent.CountDownLatch;public class MainThread {public static void main(String[] args) {ThreadExecutor executor = new ThreadExecutor("A", 3);executor.execute();} }class ThreadExecutor {private String prefix;private int size;public ThreadExecutor(String prefix, int size) {this.prefix = prefix;this.size = size;}public void execute() {System.out.println(prefix + " begin.");ThreadA temp = null;CountDownLatch cDownLatch = new CountDownLatch(size);for (int i = 0; i < size; i++) {temp = new ThreadA(cDownLatch, prefix + i);MyThreadPool.getInstance().execute(temp);}try {cDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(prefix + " end.");} } 主線程

執行結果

A begin.
A0 begin.
A1 begin.
A2 begin.
A1 end.
A0 end.
A2 end.
A end.

?

轉載于:https://www.cnblogs.com/BensonHe/p/3150516.html

總結

以上是生活随笔為你收集整理的一种父线程阻塞等待子线程的有效方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。