package com.yby7;
class Cleck{
private int productcount = 0;
//生产产品
public synchronized void produceproduct(){
if (productcount < 20){
productcount ++;
System.out.println(Thread.currentThread().getName()+"开始生产第"+productcount+"个产品");
notify();
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费产品
public synchronized void consumerproduct(){
if (productcount > 0){
System.out.println(Thread.currentThread().getName()+"开始消费第"+productcount+"个产品");
productcount --;
notify();
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//*********************************************************************************
class Producer implements Runnable{//生产者
private Cleck cleck;
public Producer(Cleck cleck){
this.cleck = cleck;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始生产产品...");
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
cleck.produceproduct();
}
}
}
//*********************************************************************************
class Customer implements Runnable{//消费者
private Cleck cleck;
public Customer(Cleck cleck){
this.cleck = cleck;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始消费产品...");
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
cleck.consumerproduct();
}
}
}
//*********************************************************************************
public class ProduceTest {
public static void main(String[] args) {
Cleck cleck = new Cleck();
Producer p1 = new Producer(cleck);
Thread t1 = new Thread(p1);
t1.setName("生产者1");
Customer p2 = new Customer(cleck);
Thread t2 = new Thread(p2);
t2.setName("消费者1");
t1.start();
t2.start();
}
}