package java1;
class Clerk{
private int productCount = 0;
public synchronized void produceProduct() {
if (productCount<20){
productCount++;
notify();
System.out.println(Thread.currentThread().getName()+ " 开始生产第 "+productCount+" 产品。。。");
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void comsumeProduct() {
if (productCount>0){
System.out.println(Thread.currentThread().getName()+ " 开始消费第 "+productCount+" 产品。。。");
productCount--;
notify();
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer extends Thread{
private Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+ " :开始生产。。。");
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.produceProduct();
}
}
}
class Customer extends Thread{
private Clerk clerk;
public Customer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+ " :开始消费。。。");
while (true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.comsumeProduct();
}
}
}
public class ProductTest {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer p1 = new Producer(clerk);
Producer p2 = new Producer(clerk);
p1.setName("生产者1");
p2.setName("生产者2");
p1.start();
p2.start();
Customer c1 = new Customer(clerk);
Customer c2 = new Customer(clerk);
c1.setName("消费者1");
c2.setName("消费者2");
c1.start();
c2.start();
}
}