首页 > 编程语言 > 详细

JAVA集合框架中线程安全问题

时间:2020-08-03 16:57:19      阅读:73      评论:0      收藏:0      [点我收藏+]

1、ArraryList相关

 ArrayList是线程不安全的,在多线程下同时操作一个线程会出java.util.ConcurrentModificationException异常(并发修改异常),如下所示:

    public static void main(String[] args) throws IOException {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, "thread" + i).start();
        }
    }

  解决办法:① 、使用List<String> list = new Vector<>();

       ②、 使用List<String> list = Collections.synchronizedList(new ArrayList<>());

       ③、 使用List<String> list = new CopyOnWriteArrayList<>();

Vector线程安全原因:

    /**
     * Appends the specified element to the end of this Vector.
     *
     * @param e element to be appended to this Vector
     * @return {@code true} (as specified by {@link Collection#add})
     * @since 1.2
     */
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

CopyOnWriteArrayList线程安全原因:

/**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }

Vector

 

 

2、HashSet相关

 

3、HashMap相关

JAVA集合框架中线程安全问题

原文:https://www.cnblogs.com/zblwyj/p/13426900.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!