In concurrent programming, the use of containers is often encountered. But if a container is not thread-safe, then the process of inserting or deleting multiple threads
There will be a variety of problems, is the problem of non-synchronization. So the JDK provides a thread-safe container that allows the container to be securely plugged in multi-threaded situations.
Import and delete. Of course, there are two types of thread-safe containers, the first of which is non-blocking, and non-blocking means when the request for a container is empty or the request
The exception is reported when it cannot be executed, and the second block means that a command that cannot be executed does not report an exception, and he waits until he can execute it. Below
We implement an example where multiple threads are going to insert a lot of data into the container, while another thread goes to a lot of pop data.
The code is as follows
Package Com.bird.concursey.charpet9;import Java.util.concurrent.concurrentlinkeddeque;public Class AddTask Implements Runnable {private concurrentlinkeddeque<string> list;public addtask (concurrentlinkeddeque< String> list) {super (); this.list = list;} @Overridepublic void Run () {String name = Thread.CurrentThread (). GetName (); for (int i = 0; i <; i++) {List.add (name + i);}}}
Package Com.bird.concursey.charpet9;import Java.util.concurrent.concurrentlinkeddeque;public Class PollTask Implements Runnable {private concurrentlinkeddeque<string> list;public polltask (concurrentlinkeddeque< String> list) {super (); this.list = list;} @Overridepublic void Run () {for (int i = 0; i < i++) {List.pollfirst (); List.polllast ();}} public static void Main (string[] args) {concurrentlinkeddeque<string> list = new concurrentlinkeddeque<string& gt; (); Thread threads[] = new Thread[100];for (int i = 0; i <; i++) {AddTask task = new AddTask (list); Threads[i] = new thre Ad (Task); Threads[i].start ();} System.out.printf ("Main:%d AddTask threads has been launched\n", threads.length); for (int i = 0; i < threads.length; i+ +) {try {threads[i].join ();} catch (Interruptedexception e) {e.printstacktrace ()}} System.out.printf ("Main:size of the List:%d\n", list.size ()); for (int i=0; i< threads.length; i++) {Polltask task = new Polltask (list); Threads[i] = new threAd (Task); Threads[i].start ();} System.out.printf ("Main:%d Polltask threads has been launched\n", threads.length); for (int i = 0; i < threads.length; I + +) {try {threads[i].join ();} catch (Interruptedexception e) {e.printstacktrace ();}} System.out.printf ("Main:size of the List:%d\n", list.size ());}}
Java Multi-thread ~ ~ ~ Non-blocking containers for thread-safe containers