public class Clerk {
public static int productCount = 0;
public static void main(String[] args) {
Thread p1 = new Thread(new Producer(new Clerk()));
p1.setName("生产者一号");
Thread c1 = new Thread(new Customer(new Clerk()));
c1.setName("消费者一号");
p1.start();
c1.start();
}
}
/*
生产者
*/
class Producer implements Runnable {
private Clerk clerk;
int count = Clerk.productCount;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public synchronized void run() {
while (true) {
if (count < 20) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
System.out.println(Thread.currentThread().getName() + ":生产了第" + count + "个商品");
notify();
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/*
消费者
*/
class Customer implements Runnable {
private Clerk clerk;
int count = Clerk.productCount;
public Customer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public synchronized void run() {
while (true) {
if (count > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
count--;
System.out.println(Thread.currentThread().getName() + ":购买了第" + count + "个商品");
notify();
} else {
System.out.println("货已售空,等待商家生产");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}