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

本文介绍如何使用ReentrantLock和Condition实现自定义的BlockingQueue,并对比了ArrayBlockingQueue的使用,强调了多线程环境下Blocking集合的安全性和便利性。

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");
    }
}

1418970-20190613123711859-1656906421.png
1418970-20190613125222851-1359401381.png
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值