总体思路:
两个类:ProConsumer用于制造两个线程做测试;ShareData有共享变量和两个方法,分别是生产方法increment(),消费decrement()
同步:使用 lock+condition
生产和消费方法模板步骤:
1.加锁
2.判断
3.等待
4.干活
5.通知唤醒
6.释放锁
package com.concurrent;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 传统版生产者消费者模式
*/
public class ProConsumer {
//主方法,制造两个线程A,B,分别生产5次和消费5次
public static void main(String[] args){
ShareDate shareDate =new ShareDate();
new Thread(()->{
for (int i=0;i<5;i++){
try{
shareDate.increment();
}catch(Exception e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i=0;i<5;i++){
try{
shareDate.decrement();
}catch(Exception e) {
e.printStackTrace();
}
}
},"B").start();
}
}
/*************************************分割线****************************/
@SuppressWarnings("all")
class ShareDate{
private int number;
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();
}
}
}