
思路:
生产者判读是否大于20: 若 否,则生产一个产品并且唤醒(消费者).若是,则堵塞.
消费者判读是否大于0,若是,则消费一个产品,并唤醒(生产者).若否,则堵塞.
我们将生产和消费的方法,放到店员类,这样可以操作共享数据.

package com.LearnJava.Thread;
class Clerk {
private int products=0;
public synchronized void prodectOne(){
if(products<20){
products++;
System.out.println(Thread.currentThread().getName()+"生产第"+products+"个产品");
notifyAll();
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void consumeOne(){
if(products>0){
System.out.println(Thread.currentThread().getName()+"消费第"+products+"个产品");
products--;
notifyAll();
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Productor extends Thread{
private Clerk c;
Productor(Clerk c){
this.c=c;
}
@Override
public void run() {
while (true){
c.prodectOne();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Customer extends Thread{
private Clerk c;
Customer(Clerk c){
this.c=c;
}
@Override
public void run() {
while (true){
c.consumeOne();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class PCCProblem {
public static void main(String[] args) {
Clerk c = new Clerk();
Productor p1 = new Productor(c);
Productor p2 = new Productor(c);
Customer c1 = new Customer(c);
p1.start();
p2.start();
c1.start();
}
}
来源:https://www.cnblogs.com/superxuezhazha/p/12283995.html
