在并发编程中,会经常遇到使用容器。但是如果一个容器不是线程安全的,那么他在多线程的插入或者删除的过程
中就会出现各种问题,就是不同步的问题。所以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; } @Override public 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; } @Override public 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()); } }