List,Set,Map在遍历过程中是不允许更新操作的(增,删,该);
非阻塞式集合(Non-Blocking Collection) ConcurrentLinkedDeque:
这类集合包括添加和移除数据的方法。如果方法不能立即被执行,则返回null或抛出异常,但是调用这个方法的线程不会被阻塞。
阻塞式集合(Blocking Collection) LinkedBlockingDeque:
阻塞式集合(Blocking Collection):这类集合包括添加和移除数据的方法。当集合已满或为空时,被调用的添加或者移除方法就不能立即被执行,那么调用这个方法的线程将被阻塞,一直到该方法可以被成功执行。
非阻塞式集合类的使用示例:
1 /**
2 * 非阻塞式并发集合
3 * 添加大量的数据到一个列表中;
4 * 从同一个列表中移除大量的数据。
5 * @author Administrator
6 *
7 */
8 public class CollectionDemo01 {
9
10 public static void main(String[] args) throws Exception {
11 //使用多线程环境下非阻塞的集合类
12 ConcurrentLinkedDeque<String> list = new ConcurrentLinkedDeque<>();
13
14 //添加数据
15 Thread[] add = new Thread[100];
16 for (int i = 0; i < add.length; i++) {
17 add[i] = new Thread(()->{
18 for (int j = 0; j < 10000; j++) {
19 list.add(Thread.currentThread().getName()+":Element "+j);
20 }
21 });
22 add[i].start();
23 add[i].join();
24 }
25 System.out.println("after add size"+list.size());
26 //移除数据
27 Thread[] poll = new Thread[100];
28 for (int i = 0; i < poll.length; i++) {
29 poll[i] = new Thread(()->{
30 for (int j = 0; j < 5000; j++) {
31 //移除尾部
32 list.pollLast();
33 //移除头部
34 list.pollFirst();
35 }
36 });
37 poll[i].start();
38 poll[i].join();
39 }
40 System.out.println("after poll size:"+list.size());
41 }
42
43 }
阻塞式集合类的使用示例:
1 /**
2 * 阻塞式并发集合
3 * @author Administrator
4 *
5 */
6 public class CollectionDemo02 {
7
8 public static void main(String[] args) {
9 //使用多线程下的阻塞式并发集合类
10 LinkedBlockingDeque<String> list = new LinkedBlockingDeque<>(5);
11 //添加数据
12 Thread thread = new Thread(()->{
13 for (int i = 0; i < 3; i++) {
14 for (int j = 0; j < 5; j++) {
15 String str = new String(i+":"+j);
16 try {
17 list.put(str.toString());
18 System.out.println("client:"+str+(new Date()));
19 } catch (InterruptedException e) {
20 e.printStackTrace();
21 }
22 }
23 }
24 });
25 thread.start();
26
27 //取数据
28 for (int i = 0; i < 5; i++) {
29 for (int j = 0; j < 3; j++) {
30 try {
31 System.out.println("main:before take size:"+list.size());
32 //从集合中取出数据
33 String str = list.take();
34 System.out.println("main:after take"+str+" size:"+list.size());
35 } catch (InterruptedException e) {
36 e.printStackTrace();
37 }
38 try {
39 TimeUnit.SECONDS.sleep(2);
40 } catch (InterruptedException e) {
41 e.printStackTrace();
42 }
43 }
44 }
45 System.out.println("end=========");
46 }
47 }