日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/7/25 121 豆豆
生活随笔 收集整理的這篇文章主要介紹了 廖雪峰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集合的全部內容,希望文章能夠幫你解決所遇到的問題。

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