写一个生产者和消费者,生产 – 生产 – 生产 – 生产,这样子循环。
public class ShareData {
private volatile int num=0;
private Lock lock=new ReentrantLock();
private Condition condition=lock.newCondition();
public void increment(){
try {lock.lock();
while (num!=0){condition.await();
}
num++;
System.out.println("线程 --"+ Thread.currentThread().getName()+"执行了减少操作,num-->"+num);
condition.signalAll();}catch (Exception e){e.printStackTrace();
}finally {lock.unlock();
}
}
public void decrement(){
try {lock.lock();
while (num==0){condition.await();
}
num--;
System.out.println("线程 --"+ Thread.currentThread().getName()+"执行了缩小操作,num-->"+num);
condition.signalAll();}catch (Exception e){e.printStackTrace();
}finally {lock.unlock();
}
}
}
public static void main(String[] args) {ShareData data=new ShareData();
for (int i=0;i<5;i++){new Thread(()->{data.increment();
},"AAA").start();}
for (int i=0;i<5;i++){new Thread(()->{data.decrement();
},"BBB").start();}
}
2 个线程,一个生产,一个生产。生产者 increment 之后,唤醒消费者,消费者开始生产。