package com.dnaer.core.sale.saleinvitelog.util; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class MySource{ public static volatile boolean TAG = false; // 如果是 1 就消费,如果是0 就生产 private int num = 0; Lock lock = new ReentrantLock(); Condition c = lock.newCondition(); public void pro() { try { lock.lock(); while (TAG) { if (num != 0) { c.await(); } TimeUnit.SECONDS.sleep(1); num++; System.out.println("生产者,生产数据:"+num); c.signal(); } }catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } public void cons () { try { lock.lock(); while (TAG) { if (num != 1) { c.await(); } System.out.println("\t\t消费者,生产数据:"+num); num--; c.signal(); } }catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } } public class ThreadTest { public static void main(String[] args) { MySource.TAG = true; MySource mySource = new MySource(); new Thread(() ->{ mySource.pro(); }).start(); new Thread(() ->{ mySource.cons(); }).start(); try { TimeUnit.SECONDS.sleep(6); }catch (Exception e) { e.printStackTrace(); } MySource.TAG = false; } }