標籤:tar read stack style print new t join tac class
在並發編程中,會常常遇到使用容器。可是假設一個容器不是安全執行緒的。那麼他在多線程的插入或者刪除的過程
中就會出現各種問題。就是不同步的問題。所以JDK提供了安全執行緒的容器,他能保證容器在多線程的情況下安全的插
入和刪除。當然,安全執行緒的容器分為兩種,第一種為非堵塞似的,非堵塞的意思是當請求一個容器為空白或者這個請求
不能啟動並執行時候。就會報出異常,另外一種堵塞的意思是,不能啟動並執行命令不會報出異常。他會等待直到他能運行。以下
我們實現一個範例,這個範例就是多個線程去大量的插入容器資料。而還有一個線程去大量的pop出資料。
代碼例如以下
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 < 1000; 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 < 5000; i++) {list.pollFirst();list.pollLast();}}public static void main(String[] args) {ConcurrentLinkedDeque<String> list = new ConcurrentLinkedDeque<String>();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());}}
Java多線程之~~~安全執行緒容器的非堵塞容器