Function: 数组实现的线程安全阻塞队列 @author crossoverJie Date: 2019-04-04 15:02 @since JDK 1.8
| 8 | * @since JDK 1.8 |
| 9 | */ |
| 10 | public final class ArrayQueue<T> { |
| 11 | |
| 12 | /** |
| 13 | * 队列数量 |
| 14 | */ |
| 15 | private int count = 0; |
| 16 | |
| 17 | /** |
| 18 | * 最终的数据存储 |
| 19 | */ |
| 20 | private Object[] items; |
| 21 | |
| 22 | /** |
| 23 | * 队列满时的阻塞锁 |
| 24 | */ |
| 25 | private Object full = new Object(); |
| 26 | |
| 27 | /** |
| 28 | * 队列空时的阻塞锁 |
| 29 | */ |
| 30 | private Object empty = new Object(); |
| 31 | |
| 32 | |
| 33 | /** |
| 34 | * 写入数据时的下标 |
| 35 | */ |
| 36 | private int putIndex; |
| 37 | |
| 38 | /** |
| 39 | * 获取数据时的下标 |
| 40 | */ |
| 41 | private int getIndex; |
| 42 | |
| 43 | public ArrayQueue(int size) { |
| 44 | items = new Object[size]; |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * 从队列尾写入数据 |
| 49 | * @param t |
| 50 | */ |
| 51 | public void put(T t) { |
| 52 | |
| 53 | synchronized (full) { |
| 54 | while (count == items.length) { |
| 55 | try { |
| 56 | full.wait(); |
| 57 | } catch (InterruptedException e) { |
| 58 | break; |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | synchronized (empty) { |
| 64 | //写入 |
| 65 | items[putIndex] = t; |
| 66 | count++; |
| 67 |
nothing calls this directly
no outgoing calls
no test coverage detected