线程简单知识(并发容器)

ConcurrentMap:

    ConcurrentHashMap:将map 分段(segment,默认为16段)处理,每一段就像一个HashTable一样。细粒度的思想。

    

CopyOnWrite:写时复制容器,在进行写操作时,先将当前容器copy一个副本,先修改副本中的内容,然后在赋值给元容器。这样在读取时是没有任何效率上的影响的。

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();
        }
    }

ConcurrentLinkedQueue:无界的适用于高并发,遵循先进先出的Queue;

BlockIngQueue:阻塞队列

    ArrayBlockingQueue:有界的

public ArrayBlockingQueue(int capacity)     // 必须传入界限参数
public ArrayBlockingQueue(int capacity, boolean fair)
public boolean add(E e)     // add 和  offer  一样 都返回boolean
public boolean offer(E e)
public void put(E e) throws InterruptedException {    
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == items.length)
            notFull.await();  //put 方法会有等待
    enqueue(e);
    } finally {
        lock.unlock();
    }
}

    LinkedBlockingQueue:无界

public LinkedBlockingQueue()      //传参就是有界的队列
public LinkedBlockingQueue(int capacity)
public void put(E e)       // 已经满了,会等待
public boolean offer(E e)     // 填不进去返回false
public E take()          //没取到值会等待
public E poll()            //没取到值返回null
public E peek()            //没取到值返回null

    SynchronousQueue:没有空间的Queue.

PriorityBlockingQueue:给予优先级的阻塞队列,无界队列

public PriorityBlockingQueue()        // 默认界限为11
public PriorityBlockingQueue(int initialCapacity)   // 自己传入界限
public PriorityBlockingQueue(int initialCapacity,     //自定义优先级比较方法
                             Comparator<? super E> comparator)
public PriorityBlockingQueue(Collection<? extends E> c)   //传入集合
public boolean offer(E e)   // add put 都相同,若初始化时没有定义优先级比较方法,传入的参数必须实现了Comparator接口。
/**
 * Mechanics for poll().  Call only while holding lock.
 */
private E dequeue() {    //在取值的时候会排序(有很多人以为在添加的时候排序的,实际上时取值时)
    int n = size - 1;
    if (n < 0)
        return null;
    else {
        Object[] array = queue;
        E result = (E) array[0];
        E x = (E) array[n];
        array[n] = null;
        Comparator<? super E> cmp = comparator;
        if (cmp == null)
            siftDownComparable(0, x, array, n);
        else
            siftDownUsingComparator(0, x, array, n, cmp);
        size = n;
        return result;
    }
}
public int drainTo(Collection<? super E> c)    // 将数据转换为集合c取出来
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值