Liao Xuefeng Java11 -3 senior concurrent multi-threaded programming package -4Concurrent collection

Concurrent

With ReentrantLock + Condition achieve Blocking Queue.
Blocking Queue: When a thread calls getTask (), this method may give internal thread into a wait state until the conditions are met. After the thread wakes, getTask () will return, but java.util.concurrent provides Blocking collections thread-safe, such as 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 tools also provide the old thread-safe collection converter:
such as put into a HashMap HashMap thread-safe:

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

The actual use of a packaging, packaging non-thread-safe Map, then all are locked with a synchronized way, so get a set of thread-safe, the performance is much lower than the Concurrent, not recommended.

to sum up:

Use java.util.concurrent provides Blocking can simplify the collection of multi-threaded programming

  • Blocking multiple threads simultaneously access the collection is safe
  • Try to use concurrent collection of the JDK, avoid writing their own synchronization code

Guess you like

Origin www.cnblogs.com/csj2018/p/11016289.html