目的:保证商品不多于20个,不少于0个,且当商品为20个时暂停生产并且通知消费者消费,为0个时则通知消费者无货。
注意点:注意 if 语句的选择(if 放什么、else 放什么)
public class TestProduct {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Consumer con = new Consumer(clerk);
Producer pro = new Producer(clerk);
Thread t1 = new Thread(con);
Thread t2 = new Thread(con);
Thread t3 = new Thread(pro);
Thread t4 = new Thread(pro);
t1.setName("1");
t2.setName("2");
t3.setName("1");
t4.setName("2");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Clerk {
int numOfProduction;// 共享資源
public synchronized void produce() {// 定义生产共享资源的方法
if (numOfProduction == 20) {// 达到20个则暂停生产,否则继续生产并且唤醒消费
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
numOfProduction++;
System.out.println(Thread.currentThread().getName() + "号生产者生产了货架上第" + numOfProduction + "号产品");
notifyAll();
}
}
public synchronized void consume() {// 定义消费共享资源的方法
if (numOfProduction == 0) {// 达到0个则暂停消费,否则继续消费并且唤醒生产
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "号消费者消费了货架上第" + numOfProduction + "号产品");
numOfProduction--;
notifyAll();// 已消费,唤醒生产者生产
}
}
}
class Producer implements Runnable {
Clerk clerk;
public Producer(Clerk clerk) {
super();
this.clerk = clerk;
}
@Override
public void run() {
while (true) {
clerk.produce();
}
}
}
class Consumer implements Runnable {
Clerk clerk;
public Consumer(Clerk clerk) {
super();
this.clerk = clerk;
}
@Override
public void run() {
while (true) {
clerk.consume();
}
}
}
时间: 2024-11-15 20:43:06