借助JUC
里的ReentrantLock
实现一个阻塞队列结构:
代码块11 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| package demo.concurrent.lock.queue;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock;
public class SimpleQueue {
private static ReentrantLock lock = new ReentrantLock();
private T[] nodes;
private int tail = 0;
private int count = 0;
private int head = 0;
public SimpleQueue(int size) { nodes = (T[]) new Object[size]; }
private static Condition notFull = lock.newCondition();
private static Condition notEmpty = lock.newCondition();
public void put(T t) { try { lock.lock(); if (count == nodes.length) { System.out.println("目前队列已满,等待取值中"); notFull.await(); } if (tail > (nodes.length - 1)) { tail = 0; } nodes[tail] = t; count++; tail++; notEmpty.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } }
public T take() { T t = null; try { lock.lock(); if (count == 0) { System.out.println("目前队列已空,等待入值中"); notEmpty.await(); } if (head > (nodes.length - 1)) { head = 0; } t = nodes[head]; nodes[head] = null; head++; count--; notFull.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); }
return t; }
}
|
以上为主要代码,下面进行简单的测试:
代码块21 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| @Test public void simpleQueueTest() throws Exception {
executorService.execute(() -> { simpleQueue.put(1); simpleQueue.put(2); simpleQueue.put(3); simpleQueue.put(4); simpleQueue.put(5); simpleQueue.put(6);
simpleQueue.put(7); simpleQueue.put(8); simpleQueue.put(9); simpleQueue.put(10); simpleQueue.put(11); simpleQueue.put(12); });
Thread.sleep(5000L);
executorService.execute(() -> {
Integer r; while ((r = simpleQueue.take()) != null) { System.out.println(r); } });
Thread.sleep(5000L); }
|
运行结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 目前队列已满,等待取值中 目前队列已满,等待取值中 1 2 目前队列已满,等待取值中 3 目前队列已满,等待取值中 4 5 6 7 8 9 目前队列已空,等待入值中 10 11 12 目前队列已空,等待入值中
|