Java multithreading ~~~ Non-blocking containers of thread-Safe Containers
Containers are often used in concurrent programming. However, if a container is not thread-safe, it is inserted or deleted in multiple threads.
There will be various problems, that is, the problem of non-synchronization. Therefore, JDK provides a thread-Safe Container, which can ensure secure plug-in of containers in the case of multiple threads.
Import and delete. Of course, there are two types of thread-Safe Containers. The first type is non-blocking. Non-blocking means that when a request to a container is empty or this request
When the command cannot be executed, an exception is reported. The second blocking means that the command that cannot be executed will not report an exception, and he will wait until the command can be executed. Below
Here is an example. Multiple Threads insert a large amount of container data, while the other thread outputs a large amount 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
list;public AddTask(ConcurrentLinkedDeque
list) {super();this.list = list;}@Overridepublic void run() {String name = Thread.currentThread().getName();for(int i = 0; i < 1000; i++) {list.add(name + i);}}}
package com.bird.concursey.charpet9;import java.util.concurrent.ConcurrentLinkedDeque;public class PollTask implements Runnable {private ConcurrentLinkedDeque
list;public PollTask(ConcurrentLinkedDeque
list) {super();this.list = list;}@Overridepublic void run() {for(int i = 0; i < 5000; i++) {list.pollFirst();list.pollLast();}}public static void main(String[] args) {ConcurrentLinkedDeque
list = new ConcurrentLinkedDeque
();Thread threads[] = new Thread[100];for(int i = 0; i < 100; i++) {AddTask task = new AddTask(list);threads[i] = new Thread(task);threads[i].start();}System.out.printf("Main: %d AddTask threads have 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 have 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());}}