package time_3_22;
class Clerk{
private int num = 0;
public synchronized void produceProductor(){
if(num < 20){
num++;
System.out.println(Thread.currentThread().getName() + ":开始生产第" + num + "产品");
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void produceCustomer(){
if(num > 0){
System.out.println(Thread.currentThread().getName() + ":开始消费第" + num + "产品");
num--;
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Productor extends Thread{
private Clerk clerk;
public Productor(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.produceProductor();
}
}
}
class Customer_2 extends Thread{
private Clerk clerk;
public Customer_2(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.produceCustomer();
}
}
}
public class ProductTest {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Productor p1 = new Productor(clerk);
Customer_2 c2 = new Customer_2(clerk);
p1.setName("生产者");
c2.setName("消费者");
p1.start();
c2.start();
}
}