import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 描述:生产者消费者 2.0 lock-Condition 版 * * Thread1 对 number 加 1 * Thread2 对 number 减 1 * * @author 小纸人 * @create 2019-07-31 21:40 */ class ShareData2 { private int number = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); public void increment() throws Exception { lock.lock(); try { //1、判断 while (number != 0){ //等待不生产 condition.await(); } //2.干活 number++; System.out.println(Thread.currentThread().getName() + "\t" + number); //3. 通知唤醒 condition.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void decrement() throws Exception { lock.lock(); try { //1、判断 while (number == 0){ //等待 不消费 condition.await(); } //2.干活 number--; System.out.println(Thread.currentThread().getName() + "\t" + number); //3. 通知唤醒 condition.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } public class Version2_0 { public static void main(String[] args){ ShareData2 shareData2 = new ShareData2(); new Thread(() -> { for (int i = 0; i < 5; i++) { try { shareData2.increment(); } catch (Exception e) { e.printStackTrace(); } } },"AAA").start(); new Thread(() -> { for (int i = 0; i < 5; i++) { try { shareData2.decrement(); } catch (Exception e) { e.printStackTrace(); } } },"BBB").start(); } }
生产者消费者2.0(lock)
最新推荐文章于 2023-05-17 08:15:00 发布