前言:
Java基础知识不错的同学应该还记得,
常用的数据结构是线程不安全的 ,例如ArrayList, HashMap, HashSet
他们都是非同步的 ,当多个线程同时读写,可能会抛出异常或数据错误 。
而传统的Vector,Hashtable等同步集合性能过差 ,因此我们急需要一种能够满足高并发的数据结构,java.util.concurrent包里就提供了以下两类数据结构,实现数据添加和删除
–阻塞式集合:当集合为空或者满时,等待
–非阻塞式集合:当集合为空或者满时,不等待,返回null或异常
下面,我们来具体分析一下不同的数据结构的特点:
• List
–Vector 同步安全,写多读少,适用于频繁修改数据的场合,但对于读取(遍历数据)的情况较少
–ArrayList 不安全
–Collections.synchronizedList(List list) 基于synchronized,但是由于加锁机制的特点,使得这个数据结构的效率较差
–CopyOnWriteArrayList 适用于读多写少的情况,是一种基于复制机制的并发列表类,非阻塞式,性能较优
• Set
–HashSet 不安全,不适合多线程环境
–Collections.synchronizedSet(Set set)基于synchronized,效率差
–CopyOnWriteArraySet(基于CopyOnWriteArrayList实现) 读多写少, 非阻塞
• Map
–Hashtable同步安全,写多读少
–HashMap 不安全
–Collections.synchronizedMap(Map map) 基于synchronized,效率差
–ConcurrentHashMap读多写少,非阻塞
• Queue (单向队列)& Deque (双向队列)
– 遵循FIFO(先进先出)的特点
–ConcurrentLinkedQueue非阻塞
–ArrayBlockingQueue/LinkedBlockingQueue阻塞
下面我们来通过几个代码的实例展示各种数据结构的特点及安全性:
• List实例:
三种不同的List在多线程环境下,分别尝试插入100个元素到list中
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class ListTest {
public static void main(String[] args) throws InterruptedException{
//线程不安全
List<String> unsafeList = new ArrayList<String>();
//线程安全
List<String> safeList1 = Collections.synchronizedList(new ArrayList<String>());
//线程安全
CopyOnWriteArrayList<String> safeList2 = new CopyOnWriteArrayList<String>();
ListThread t1 = new ListThread(unsafeList);
ListThread t2 = new ListThread(safeList1);
ListThread t3 = new ListThread(safeList2);
for(int i = 0; i < 10; i++){
Thread t = new Thread(t1, String.valueOf(i));
t.start();
}
for(int i = 0; i < 10; i++) {
Thread t = new Thread(t2, String.valueOf(i));
t.start();
}
for(int i = 0; i < 10; i++) {
Thread t = new Thread(t3, String.valueOf(i));
t.start();
}
//等待子线程执行完
Thread.sleep(2000);
System.out.println("listThread1.list.size() = " + t1.list.size());
System.out.println("listThread2.list.size() = " + t2.list.size());
System.out.println("listThread3.list.size() = " + t3.list.size());
//输出list中的值
System.out.println("unsafeList:");
for(String s : t1.list){
if(s == null){
System.out.print("null ");
}
else
{
System.out.print(s + " ");
}
}
System.out.println();
System.out.println("safeList1:");
for(String s : t2.list){
if(s == null){
System.out.print("null ");
}
else
{
System.out.print(s + " ");
}
}
System.out.println();
System.out.println("safeList2:");
for(String s : t3.list){
if(s == null){
System.out.print("null ");
}
else
{
System.out.print(s + " ");
}
}
}
}
class ListThread implements Runnable{
public List<String> list;
public ListThread(List<String> list){
this.list = list;
}
@Override
public void run() {
int i = 0;
while(i<10)
{
try {
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
//把当前线程名称加入list中
list.add(Thread.currentThread().getName());
i++;
}
}
}
运行结果如下所示,我们可以看到,ArrayList不安全,插入的元素只有64个,而剩下两个都是线程安全的,符合了我们的要求
• Set实例
同上List的实例,分别放入100个元素
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
public class SetTest{
public static void main(String[] args) throws InterruptedException{
//线程不安全
Set<String> unsafeSet = new HashSet<String>();
//线程安全
Set<String> safeSet1 = Collections.synchronizedSet(new HashSet<String>());
//线程安全
CopyOnWriteArraySet<String> safeSet2 = new CopyOnWriteArraySet<String>();
SetThread t1 = new SetThread(unsafeSet);
SetThread t2 = new SetThread(safeSet1);
SetThread t3 = new SetThread(safeSet2);
//unsafeSet的运行测试
for(int i = 0; i < 10; i++){
Thread t = new Thread(t1, String.valueOf(i));
t.start();
}
for(int i = 0; i < 10; i++) {
Thread t = new Thread(t2, String.valueOf(i));
t.start();
}
for(int i = 0; i < 10; i++) {
Thread t = new Thread(t3, String.valueOf(i));
t.start();
}
//等待子线程执行完
Thread.sleep(2000);
System.out.println("setThread1.set.size() = " + t1.set.size());
System.out.println("setThread2.set.size() = " + t2.set.size());
System.out.println("setThread3.set.size() = " + t3.set.size());
//输出set中的值
System.out.println("unsafeSet:");
for(String element:t1.set){
if(element == null){
System.out.print("null ");
}
else
{
System.out.print(element + " ");
}
}
System.out.println();
System.out.println("safeSet1:");
for(String element:t2.set){
if(element == null){
System.out.print("null ");
}
else
{
System.out.print(element + " ");
}
}
System.out.println();
System.out.println("safeSet2:");
for(String element:t3.set){
if(element == null){
System.out.print("null ");
}
else
{
System.out.print(element + " ");
}
}
}
}
class SetThread implements Runnable{
public Set<String> set;
public SetThread(Set<String> set){
this.set = set;
}
@Override
public void run() {
int i = 0;
while(i<10)
{
i++;
try {
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
//把当前线程名称加入list中
set.add(Thread.currentThread().getName() + i);
}
}
}
运行结果如下,我们发现,HsahSet不安全,其余两个都是线程安全的
• Map实例
多个线程分别将自己的名称添加到映射中
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class MapTest{
public static void main(String[] args) throws InterruptedException{
//线程不安全
Map<Integer,String> unsafeMap = new HashMap<Integer,String>();
//线程安全
Map<Integer,String> safeMap1 = Collections.synchronizedMap(new HashMap<Integer,String>());
//线程安全
ConcurrentHashMap<Integer,String> safeMap2 = new ConcurrentHashMap<Integer,String>();
MapThread t1 = new MapThread(unsafeMap);
MapThread t2 = new MapThread(safeMap1);
MapThread t3 = new MapThread(safeMap2);
//unsafeMap的运行测试
for(int i = 0; i < 10; i++){
Thread t = new Thread(t1);
t.start();
}
for(int i = 0; i < 10; i++) {
Thread t = new Thread(t2);
t.start();
}
for(int i = 0; i < 10; i++) {
Thread t = new Thread(t3);
t.start();
}
//等待子线程执行完
Thread.sleep(2000);
System.out.println("mapThread1.map.size() = " + t1.map.size());
System.out.println("mapThread2.map.size() = " + t2.map.size());
System.out.println("mapThread3.map.size() = " + t3.map.size());
//输出set中的值
System.out.println("unsafeMap:");
@SuppressWarnings("rawtypes")
Iterator iter = t1.map.entrySet().iterator();
while(iter.hasNext()) {
@SuppressWarnings("unchecked")
Map.Entry<Integer,String> entry = (Map.Entry<Integer,String>)iter.next();
// 获取key
System.out.print(entry.getKey() + ":");
// 获取value
System.out.print(entry.getValue() + " ");
}
System.out.println();
System.out.println("safeMap1:");
iter = t2.map.entrySet().iterator();
while(iter.hasNext()) {
@SuppressWarnings("unchecked")
Map.Entry<Integer,String> entry = (Map.Entry<Integer,String>)iter.next();
// 获取key
System.out.print(entry.getKey() + ":");
// 获取value
System.out.print(entry.getValue() + " ");
}
System.out.println();
System.out.println("safeMap2:");
iter = t3.map.entrySet().iterator();
while(iter.hasNext()) {
@SuppressWarnings("unchecked")
Map.Entry<Integer,String> entry = (Map.Entry<Integer,String>)iter.next();
// 获取key
System.out.print(entry.getKey() + ":");
// 获取value
System.out.print(entry.getValue() + " ");
}
System.out.println();
System.out.println("mapThread1.map.size() = " + t1.map.size());
System.out.println("mapThread2.map.size() = " + t2.map.size());
System.out.println("mapThread3.map.size() = " + t3.map.size());
}
}
class MapThread implements Runnable
{
public Map<Integer,String> map;
public MapThread(Map<Integer,String> map){
this.map = map;
}
@Override
public void run() {
int i=0;
while(i<100)
{
//把当前线程名称加入map中
map.put(i++,Thread.currentThread().getName());
try {
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
运行结果如下,可以看出HashMap不安全,其余两个时安全的:
• Queue (单向队列)& Deque (双向队列)实例
多个线程插入100个元素,比较结果
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedDeque;
public class QueueTest {
public static void main(String[] args) throws InterruptedException{
//线程不安全
Deque<String> unsafeQueue = new ArrayDeque<String>();
//线程安全
ConcurrentLinkedDeque<String> safeQueue1 = new ConcurrentLinkedDeque<String>();
ArrayBlockingQueue<String> safeQueue2 = new ArrayBlockingQueue<String>(100);
QueueThread t1 = new QueueThread(unsafeQueue);
QueueThread t2 = new QueueThread(safeQueue1);
QueueThread t3 = new QueueThread(safeQueue2);
for(int i = 0; i < 10; i++){
Thread thread1 = new Thread(t1, String.valueOf(i));
thread1.start();
}
for(int i = 0; i < 10; i++) {
Thread thread2 = new Thread(t2, String.valueOf(i));
thread2.start();
}
for(int i = 0; i < 10; i++) {
Thread thread3 = new Thread(t3, String.valueOf(i));
thread3.start();
}
//等待子线程执行完
Thread.sleep(2000);
System.out.println("queueThread1.queue.size() = " + t1.queue.size());
System.out.println("queueThread2.queue.size() = " + t2.queue.size());
System.out.println("queueThread3.queue.size() = " + t3.queue.size());
//输出queue中的值
System.out.println("unsafeQueue:");
for(String s:t1.queue)
{
System.out.print(s + " ");
}
System.out.println();
System.out.println("safeQueue1:");
for(String s:t2.queue)
{
System.out.print(s + " ");
}
System.out.println();
System.out.println("safeQueue2:");
for(String s:t3.queue)
{
System.out.print(s + " ");
}
}
}
class QueueThread implements Runnable{
public Queue<String> queue;
public QueueThread(Queue<String> queue){
this.queue = queue;
}
@Override
public void run() {
int i = 0;
while(i<10)
{
i++;
try {
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
//把当前线程名称加入list中
queue.add(Thread.currentThread().getName());
}
}
}
结果如下,很容易看出传统的ArrayDeque不安全,而剩余两个都是安全的
总结:
在多线程并发读写时,应当注意对数据读写时的安全性问题。
选择合适的数据结构存储数据,提高数据结构的使用效率,同时也将加快程序的运行速度。