|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.List; |
| 3 | +import java.util.concurrent.locks.Condition; |
| 4 | +import java.util.concurrent.locks.Lock; |
| 5 | +import java.util.concurrent.locks.ReentrantLock; |
| 6 | + |
| 7 | +/** |
| 8 | + * 手写实现 |
| 9 | + * Condition + ReentrantLock |
| 10 | + * |
| 11 | + * @Author: zzStar |
| 12 | + * @Date: 04-30-2022 23:37 |
| 13 | + */ |
| 14 | +public class BlockingQueue_2 { |
| 15 | + |
| 16 | + private List<Integer> buffer = new ArrayList<>(); |
| 17 | + private volatile int size; |
| 18 | + private volatile int capacity; |
| 19 | + private Lock lock = new ReentrantLock(); |
| 20 | + |
| 21 | + private final Condition isNull = lock.newCondition(); |
| 22 | + private final Condition isFull = lock.newCondition(); |
| 23 | + |
| 24 | + BlockingQueue_2(int capacity) { |
| 25 | + this.capacity = capacity; |
| 26 | + } |
| 27 | + |
| 28 | + private void set(int n) { |
| 29 | + try { |
| 30 | + lock.lock(); |
| 31 | + try { |
| 32 | + while (size >= capacity) { |
| 33 | + System.out.println("阻塞队列满了"); |
| 34 | + isFull.await(); |
| 35 | + } |
| 36 | + } catch (InterruptedException e) { |
| 37 | + isFull.signal(); |
| 38 | + e.printStackTrace(); |
| 39 | + } |
| 40 | + ++size; |
| 41 | + buffer.add(n); |
| 42 | + isNull.signal(); |
| 43 | + } finally { |
| 44 | + lock.unlock(); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + private int get() { |
| 49 | + try { |
| 50 | + lock.lock(); |
| 51 | + try { |
| 52 | + while (size == 0) { |
| 53 | + System.out.println("阻塞队列空了"); |
| 54 | + isNull.await(); |
| 55 | + } |
| 56 | + } catch (InterruptedException e) { |
| 57 | + isNull.signal(); |
| 58 | + e.printStackTrace(); |
| 59 | + } |
| 60 | + --size; |
| 61 | + int res = buffer.get(0); |
| 62 | + buffer.remove(0); |
| 63 | + isFull.signal(); |
| 64 | + return res; |
| 65 | + } finally { |
| 66 | + lock.unlock(); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + public static void main(String[] args) { |
| 71 | + BlockingQueue_2 qu = new BlockingQueue_2(5); |
| 72 | + Thread t1 = new Thread(() -> { |
| 73 | + for (int i = 0; i < 10; i++) { |
| 74 | + qu.set(i); |
| 75 | + System.out.println("塞入" + i); |
| 76 | + try { |
| 77 | + Thread.sleep(500); |
| 78 | + } catch (InterruptedException e) { |
| 79 | + e.printStackTrace(); |
| 80 | + } |
| 81 | + } |
| 82 | + }); |
| 83 | + Thread t2 = new Thread(() -> { |
| 84 | + while (true) { |
| 85 | + System.out.println("消费" + qu.get()); |
| 86 | + try { |
| 87 | + Thread.sleep(800); |
| 88 | + } catch (InterruptedException e) { |
| 89 | + e.printStackTrace(); |
| 90 | + } |
| 91 | + } |
| 92 | + }); |
| 93 | + t1.start(); |
| 94 | + t2.start(); |
| 95 | + } |
| 96 | + |
| 97 | +} |
0 commit comments