Java多線程之~~~安全執行緒容器的非堵塞容器

來源:互聯網
上載者:User

標籤: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多線程之~~~安全執行緒容器的非堵塞容器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.