廖雪峰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集合,避免自己编写同步代码

猜你喜欢

转载自www.cnblogs.com/csj2018/p/11016289.html
今日推荐