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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

廖雪峰Java11多线程编程-3高级concurrent包-4Concurrent集合

發布時間:2025/7/25 java 77 豆豆
生活随笔 收集整理的這篇文章主要介紹了 廖雪峰Java11多线程编程-3高级concurrent包-4Concurrent集合 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Concurrent

用ReentrantLock+Condition實現Blocking Queue。
Blocking Queue:當一個線程調用getTask()時,該方法內部可能讓給線程進入等待狀態,直到條件滿足。線程喚醒以后,getTask()才會返回,而java.util.concurrent提供了線程安全的Blocking集合,如ArrayBlockingQueue。

class TaskQueue{final Queue<String> queue = new LinkedList<>();final Lock lock = new ReentrantLock();final Condition noEmpty = lock.newCondition();public String getTask(){...}public void addTask(String name){...} } import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue;class WorkerThread extends Thread{BlockingQueue<String> taskQueue;public WorkerThread(BlockingQueue<String> taskQueue){this.taskQueue = taskQueue;}public void run(){while(!isInterrupted()){String name;try{name = taskQueue.take();}catch (InterruptedException e){break;}String result = "Hello,"+name+"!";System.out.println(result);}} } public class Main{public static void main(String[] args) throws Exception{BlockingQueue<String> taskQueue = new ArrayBlockingQueue<>(1000);WorkerThread worker = new WorkerThread(taskQueue);worker.start();taskQueue.put("Bob");Thread.sleep(1000);taskQueue.put("Alice");Thread.sleep(1000);taskQueue.put("Tim");Thread.sleep(1000);worker.interrupt();worker.join();System.out.println("END");} }



java.util.Collections工具類還提供了舊的線程安全集合轉換器:
如把一個HashMap轉化為線程安全的HashMap:

Map unsafeMap = new HashMap(); Map threadSafeMap = Collections.synchronizedMap(unsafeMap);

實際使用了一個包裝類,包裝了非線程安全的Map,然后對所有的方法都用synchronized加鎖,這樣獲得線程安全的集合,性能比Concurrent低很多,不推薦使用。

總結:

使用java.util.concurrent提供的Blocking集合可以簡化多線程編程

  • 多線程同時訪問Blocking集合是安全的
  • 盡量使用JDK提供的concurrent集合,避免自己編寫同步代碼

轉載于:https://www.cnblogs.com/csj2018/p/11016289.html

總結

以上是生活随笔為你收集整理的廖雪峰Java11多线程编程-3高级concurrent包-4Concurrent集合的全部內容,希望文章能夠幫你解決所遇到的問題。

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