深入了解JUC并发(六)并发容器

并发容器

List

ArrayList进行多线程操作:导致 ConcurrentModificationException 并发修改异常!

ArrayList 在并发情况下是不安全的

//java.util.ConcurrentModificationException 并发修改异常!
public class ListTest {
    public static void main(String[] args) {

        List<Object> arrayList = new ArrayList<>();

        for(int i=1;i<=10;i++){
            new Thread(()->{
                arrayList.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(arrayList);
            },String.valueOf(i)).start();
        }

    }
}

解决方案:

  • new Vector<>();
  • Collections.synchronizedList(new ArrayList<>());
  • new CopyOnWriteArrayList<>();
public class ListTest {
    public static void main(String[] args) {
        /**
         * 解决方案
         * 1. List<String> list = new Vector<>();
         * 2. List<String> list = Collections.synchronizedList(new ArrayList<>());
         * 3. List<String> list = new CopyOnWriteArrayList<>();
         */
        List<String> list = new CopyOnWriteArrayList<>();
        

        for (int i = 1; i <=10; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
}
CopyOnWriteArrayList
  1. 写入时复制(COW 计算机程序设计领域的一种优化策略)
  2. 在写入的时候避免覆盖,造成数据错乱的问题

CopyOnWriteArrayList对比Vector

  • Vector底层是使用synchronized关键字来实现的:效率特别低下。
  • CopyOnWriteArrayList使用的是Lock锁,效率会更加高效!

Set

HashSet进行多线程操作:导致 ConcurrentModificationException 并发修改异常!

解决方案两种:

  • Collections.synchronizedSet(new HashSet<>());
  • new CopyOnWriteArraySet<>();
public class SetTest {
    public static void main(String[] args) {
        /**
         * 1. Set<String> set = Collections.synchronizedSet(new HashSet<>());
         * 2. Set<String> set = new CopyOnWriteArraySet<>();
         */
//        Set<String> set = new HashSet<>();
        Set<String> set = new CopyOnWriteArraySet<>();

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

hashSet底层就是一个HashMap

Map

HashMap进行多线程操作:导致 java.util.ConcurrentModificationException 并发修改异常!

//map 是这样用的吗?  不是,工作中不使用这个
//默认等价什么? new HashMap<>(16,0.75);
Map<String, String> map = new HashMap<>();
//加载因子、初始化容量

默认加载因子是0.75,默认的初始容量是16

解决:

  • Collections.synchronizedMap(new HashMap<>());
  • new ConcurrentHashMap<>();
public class MapTest {
    public static void main(String[] args) {
        //map 是这样用的吗?  不是,工作中不使用这个
        //默认等价什么? new HashMap<>(16,0.75);
        /**
         * 解决方案
         * 1. Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
         *  Map<String, String> map = new ConcurrentHashMap<>();
         */
        Map<String, String> map = new ConcurrentHashMap<>();
        //加载因子、初始化容量
        for (int i = 1; i < 100; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }
}
浅谈HashTable

java.util包中提供了线程安全的HashTable,但这家伙只是通过简单的同步来实现线程安全,因此效率低。只要有一条线程获取了容器的锁之后,其他所有的线程访问同步函数都会被阻塞。

队列

队列是Collection的一个子类

在这里插入图片描述

常用队列

在这里插入图片描述

阻塞原理

在这里插入图片描述

BlockingQueue
概念

它是一个队列,在进行检索或移除一个元素的时候,它会等待队列变为非空;当在添加一个元素时,它会等待队列中的可用空间。BlockingQueue接口是Java集合框架的一部分,主要用于实现生产者-消费者模式。我们不需要担心等待生产者有可用的空间,或消费者有可用的对象,因为它都在BlockingQueue的实现类中被处理了。

ArrayBlockingQueue

数组实现的线程安全有限阻塞队列

方式抛出异常不会抛出异常,有返回值阻塞,等待超时等待
添加addofferputoffer(timenum.timeUnit)
移出removepolltakepoll(timenum,timeUnit)
判断队首元素elementpeek--
	/**
     * 抛出异常
     */
    public static void test1(){
        //需要初始化队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.add("a"));//输出true
        System.out.println(blockingQueue.add("b"));//输出true
        System.out.println(blockingQueue.add("c"));//输出true
        System.out.println(blockingQueue.add("d"));//抛出异常java.lang.IllegalStateException:队列已满
        
        System.out.println(blockingQueue.remove());//输出a
        System.out.println(blockingQueue.element());//输出b
        System.out.println(blockingQueue.remove());//输出b
        System.out.println(blockingQueue.remove());//输出c
        System.out.println(blockingQueue.remove());//如果多移除一个,这也会造成java.util.NoSuchElementException:没有元素异常
    }

	/**
     * 不抛出异常,有返回值
     */
    public static void test2(){
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        System.out.println(blockingQueue.offer("a"));//输出true
        System.out.println(blockingQueue.offer("b"));//输出true
        System.out.println(blockingQueue.offer("c"));//输出true
        System.out.println(blockingQueue.offer("d"));//会返回false 不会抛出异常
    
        System.out.println(blockingQueue.poll());//输出a
        System.out.println(blockingQueue.peek());//输出b
        System.out.println(blockingQueue.poll());//输出b
        System.out.println(blockingQueue.poll());//输出c
        System.out.println(blockingQueue.poll());//会返回null 不会抛出异常
    }

	/**
     * 等待 一直阻塞
     */
    public static void test3() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        //一直阻塞 不会返回值
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        //队列已经满了,再进去一个元素,会一直等待这个队列,什么时候有了位置再进去,程序不会停止
        blockingQueue.put("d");

        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        //这种情况也会等待阻塞,程序会一直运行
        System.out.println(blockingQueue.take());
    }

	/**
     *  等待 超时阻塞
     *  这种情况也会等待队列有位置 或者有产品 但是会超时结束
     */
    public static void test4() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        blockingQueue.offer("a");
        blockingQueue.offer("b");
        blockingQueue.offer("c");
        
        System.out.println("开始等待");
        blockingQueue.offer("d",2, TimeUnit.SECONDS);//超时时间2s 等待如果超过2s就结束等待
        System.out.println("结束等待");
        
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        
        System.out.println("开始等待");
        blockingQueue.poll(2,TimeUnit.SECONDS); //超过两秒 我们就不要等待了
        System.out.println("结束等待");
    }

LinkedBlockingQueue

单链表实现的线程安全无限阻塞队列

在这里插入图片描述

  • LinkedBlockingQueue继承自AbstractQueue,实现了BlockingQueue接口
  • LinkedBlockingQueue由单链表实现,因此是个无限队列。但为了方式无限膨胀,构造时可以加上容量加以限制
  • LinkedBlockingQueue分别采用读取锁和插入锁控制读取/删除 和 插入过程的并发访问,并采用notEmpty和notFull两个Condition实现队满队空的阻塞与唤醒
SynchronousQueue

没有容量同步队列

  • put了一个元素,就必须从里面先take出来,否则不能再put进去值
  • api:put方法 和 take方法
package com.marchsoft.queue;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

/**
 * Description:
 *
 * @author jiaoqianjin
 * Date: 2020/8/12 10:02
 **/

public class SynchronousQueue {
    public static void main(String[] args) {
        BlockingQueue<String> synchronousQueue = new java.util.concurrent.SynchronousQueue<>();
        // 网queue中添加元素
        new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "put 01");
                synchronousQueue.put("1");
                System.out.println(Thread.currentThread().getName() + "put 02");
                synchronousQueue.put("2");
                System.out.println(Thread.currentThread().getName() + "put 03");
                synchronousQueue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        // 取出元素
        new Thread(()-> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "take" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "take" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "take" + synchronousQueue.take());
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

在这里插入图片描述

关于使用选择

数组
不需要并发
  • HashMap:一般就用这个
  • TreeMap:需要排序时,使用这个
  • LinkedhashMap:有序的Map
并发不是很大时
  • Hashtable:早期的线程安全Map。速度较慢,高并发下不推荐使用
  • Collections.sychronizedXxx:将不安全的容器包装成安全的容器后返回,返回的容器则为安全的容器
高并发时
  • ConcurrentHashMap:线程安全Map,用来替代HashMap。采用粒度更细的加锁机制:分段锁,因此高并发下可以实现更高的吞吐量,单线程下也只会损失很小的性能
  • ConcurrentSkipListMap :线程安全Map,且为有序的Map,用于替代SortedMap,支持高并发。Set只需将Map换为Set即可
队列
不需要并发
  • ArrayList:最常用
  • LinkedList:支持队列操作
并发不是很大时
  • vector:早期的线程安全容器,速度较慢,高并发下不推荐使用。
  • Collections.sychronizedXxx:将不安全的容器包装成安全的容器后返回,返回的容器则为安全的容器。
高并发时
  • CopyOnWriteList:避免了高并发下的脏读现象,写入速度贼慢,读取速度快,因此适用于读多写少的情况
  • Queue(没啥特殊的,就是支持高并发而已):
    • CocurrentLinkedQueue
    • BlockingQueue:阻塞队列
      • ArrayBlockingQueue:有界的阻塞队列
      • LinkedBlockingQueue:无界的阻塞队列
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值