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) |
隊列中每一個元素都有個過時時間,而且隊列是個優先級隊列,當從隊列獲取元素時候,只有過時元素纔會出隊列數據結構
出隊源碼:會比較時間ide
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(); } }
'實現類' 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());
'彈出' 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' public class TestPrority implements Comparator { @Override public int compare(Object o1, Object o2) { return 0; } } '添加' BlockingQueue bq = new PriorityBlockingQueue<>(); bq.add(new TestPrority());