Java多线程之~~~线程安全容器的非堵塞容器

在并发编程中,会常常遇到使用容器。可是假设一个容器不是线程安全的。那么他在多线程的插入或者删除的过程

中就会出现各种问题。就是不同步的问题。所以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
",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
",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
",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
",list.size());
	}
}



原文地址:https://www.cnblogs.com/jhcelue/p/6938269.html