Clerk clerk = new Clerk();
Producer producer = new Producer(clerk);
Customer customer = new Customer(clerk);
Thread thread2 = new Thread(producer);
Thread thread3=new Thread(customer);
Thread thread4=new Thread(producer);
thread2.setName("生产者1");
thread3.setName("消费者1");
thread4.setName("生产者2");
thread2.start();
thread4.start();
thread3.start();
package com.day7.test;
public class Producer implements Runnable{
private Clerk clerk;
public Producer(Clerk clerk){
this.clerk=clerk;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.clerk.pro();
}
}
}
package com.day7.test;
public class Clerk {
private int num=0;
public synchronized void pro(){
if(num<20){
num++;
System.out.println(Thread.currentThread().getName()+"生产的第"+num+"产品");
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void Cus(){
if(num>0){
System.out.println(Thread.currentThread().getName()+"消费了第"+num+"个产品");
num--;
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.day7.test;
public class Customer implements Runnable{
private Clerk clerk;
public Customer(Clerk clerk){
this.clerk=clerk;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.clerk.Cus();
}
}
}