concurrent包的数据结构:阻塞的结构都是用lock加锁(lock会休眠锁),非阻塞是用CAS直接for循环加入。
- 结构简介
名称 | 功能 | 组成 |
---|---|---|
原子量 | ||
AtomicBoolean | Unsafe+==volatile int value== | |
AtomicInteger | Unsafe+==volatile int value== | |
AtomicIntegerArray | Unsafe+==final int[] array== | |
AtomicLong | Unsafe+==volatile long value== | |
AtomicLongArray | Unsafe+==final int[] array== |
名称 | 功能 | 组成 |
---|---|---|
阻塞队列 | ==继承:BlockingQueue接口== | |
ArrayBlockingQueue | 数组+lock | |
LinkedBlockingQueue | 链表+lock | |
PriorityBlockingQueue**(优先级队列)** | 自定义哪个队列先出 | 数组+lock |
DelayQueue (时间队列) | 队列中每个元素都有个过期时间,并且队列是个优先级队列,当从队列获取元素时候,只有过期元素才会出队列 | PriorityQueue(优先级队列)+lock |
SynchronousQueue | 一个不存储元素的阻塞队列 | |
阻塞队列(双端) | ==继承:BlockingDeque接口== | |
LinkedBlockingDeque(阻塞双端链表队列) | 链表+lock | |
非阻塞队列 | ||
ConcurrentLinkedDeque(非阻塞双端队列) | 添加线程不会休眠,一直for循环添加直到成功 | 链表(UnSafe) |
ConcurrentLinkedQueue(非阻塞队列) | 添加线程不会休眠,一直for循环添加直到成功 | 链表(UnSafe) |
其它容器 | ||
ConcurrentHashMap(非阻塞的hasMap) |
DelayQueue:延时队列。
-
队列中每个元素都有个过期时间,并且队列是个优先级队列,当从队列获取元素时候,只有过期元素才会出队列
-
出队源码:会比较时间
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
E first = q.peek();
if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
return null;
else
return q.poll();
} finally {
lock.unlock();
}
}
- 添加类:需要实现Delayed
'实现类'
public class TestDelay implements Delayed {
@Override
public int compareTo(Delayed o) {
return 0;
}
@Override
public long getDelay(TimeUnit unit) {
return 0;
}
}
'添加'
BlockingQueue bq = new DelayQueue<>();
bq.add(new TestDelay());
PriorityBlockingQueue:优先级队列
- 核心源码
'弹出'
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return dequeue();
} finally {
lock.unlock();
}
}
'调用dequeue()'
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;
}
}
'调用siftDownUsingComparator()'
private static <T> void siftDownUsingComparator(int k, T x, Object[] array,
int n,
Comparator<? super T> cmp) {
if (n > 0) {
int half = n >>> 1;
while (k < half) {
int child = (k << 1) + 1;
Object c = array[child];
int right = child + 1;
if (right < n && cmp.compare((T) c, (T) array[right]) > 0)
c = array[child = right];
if (cmp.compare(x, (T) c) <= 0)
break;
array[k] = c;
k = child;
}
array[k] = x;
}
}
- 使用:implements Comparator
'implements Comparator'
public class TestPrority implements Comparator {
@Override
public int compare(Object o1, Object o2) {
return 0;
}
}
'添加'
BlockingQueue bq = new PriorityBlockingQueue<>();
bq.add(new TestPrority());
来源:oschina
链接:https://my.oschina.net/u/2246410/blog/1800728