集合的线程安全性问题

请问ArrayList,HashSet,HashMap是线程安全的吗?如果不是我想要线程安全的集合怎么办呢?

在集合中Vector 和HashTable是线程安全的,打开源码发现其实就是把各自核心方法添加了synchornized关键字。

List list = new ArrayList<>();//线程不安全 

方法1:

List list = new Vector<>();

方法2:

List list = Collections.synchronizedList(new ArrayList<>());

 

方法3:

List list = new CopyOnWriteArrayList<>();//写时复制技术

Set set = new CopyOnWriteArraySet<>(); 

Map map = new ConcurrentHashMap<>(); 

package cn.zh.juc1205;
/**
 * 1.故障现象
 * Java.util.ConcurrentModificationException
 * 2.导致原因
 *
 * 3.解决方法
 *      3.1 new Vector<>()
 *      3.2 Collections.synchronizedList(new ArrayList<>))
 *      3.3 new CopyOnWriteArrayList()
 * 4.优化建议(同样的错误不犯第二次)
 *
 */

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class NotSafeDemo03 {

    public static void main(String[] args) {

        Map map = new ConcurrentHashMap<>();
        for (int i = 1; i <= 30;i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }

    public static void setNotSage(String[] args) {

        Set set = new CopyOnWriteArraySet<>();
        for (int i = 1; i <= 30;i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }

    }

    public static void listNodtSafe() {
        //        List list = new ArrayList<>();
//        List list = new Vector<>();
//        List list = Collections.synchronizedList(new ArrayList<>());
        //写时复制技术
        List list = new CopyOnWriteArrayList<>();
        /*list.add("a");
        list.add("b");
        list.add("c");
        list.forEach(System.out::println);//方法引用*/
        for (int i = 1; i <= 30;i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }

    }
}

 

你可能感兴趣的:(Java)