|
| 1 | +/** |
| 2 | + * @program JavaBooks |
| 3 | + * @description: ProdConsumerReentrantLock |
| 4 | + * @author: mf |
| 5 | + * @create: 2020/02/16 13:43 |
| 6 | + */ |
| 7 | + |
| 8 | +package com.juc.queue; |
| 9 | + |
| 10 | +import java.util.LinkedList; |
| 11 | +import java.util.concurrent.locks.Condition; |
| 12 | +import java.util.concurrent.locks.Lock; |
| 13 | +import java.util.concurrent.locks.ReentrantLock; |
| 14 | + |
| 15 | +public class ProdConsumerReentrantLock { |
| 16 | + |
| 17 | + private LinkedList<String> lists = new LinkedList<>(); |
| 18 | + |
| 19 | + private Lock lock = new ReentrantLock(); |
| 20 | + |
| 21 | + private Condition prod = lock.newCondition(); |
| 22 | + |
| 23 | + private Condition cons = lock.newCondition(); |
| 24 | + |
| 25 | + public void put(String s) { |
| 26 | + lock.lock(); |
| 27 | + try { |
| 28 | + // 1. 判断 |
| 29 | + while (lists.size() != 0) { |
| 30 | + // 等待不能生产 |
| 31 | + prod.await(); |
| 32 | + } |
| 33 | + // 2.干活 |
| 34 | + lists.add(s); |
| 35 | + System.out.println(Thread.currentThread().getName() + " " + lists.peekFirst()); |
| 36 | + // 3. 通知 |
| 37 | + cons.signalAll(); |
| 38 | + } catch (Exception e) { |
| 39 | + e.printStackTrace(); |
| 40 | + } finally { |
| 41 | + lock.unlock(); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + public void get() { |
| 46 | + lock.lock(); |
| 47 | + try { |
| 48 | + // 1. 判断 |
| 49 | + while (lists.size() == 0) { |
| 50 | + // 等待不能消费 |
| 51 | + cons.await(); |
| 52 | + } |
| 53 | + // 2.干活 |
| 54 | + System.out.println(Thread.currentThread().getName() + " " + lists.removeFirst()); |
| 55 | + // 3. 通知 |
| 56 | + prod.signalAll(); |
| 57 | + } catch (Exception e) { |
| 58 | + e.printStackTrace(); |
| 59 | + } finally { |
| 60 | + lock.unlock(); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + public static void main(String[] args) { |
| 65 | + ProdConsumerReentrantLock prodConsumerReentrantLock = new ProdConsumerReentrantLock(); |
| 66 | + for (int i = 0; i < 5; i++) { |
| 67 | + int tempI = i; |
| 68 | + new Thread(() -> { |
| 69 | + prodConsumerReentrantLock.put(tempI + ""); |
| 70 | + }, "ProdA" + i).start(); |
| 71 | + } |
| 72 | + for (int i = 0; i < 5; i++) { |
| 73 | + new Thread(prodConsumerReentrantLock::get, "ConsA" + i).start(); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments