1.问题
生产者将产品交给店员,而消费者从店员处取走产品,店员一次只能持有固定数量的产品(比如:20),如果生产者试图生产更多的产品,店员会叫生产者停一下。如果店中有空位放产品了再通知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下,如果店中有产品了再通知消费者来取走产品。
- 生产者:Productor
- 消费者:Customer
- 店员:Clerk
- 共享数据:店员或产品
2.使用同步机制解决线程安全问题
生产者
public class Producer extends Thread {
private Clerk clerk;
public Producer(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run(){
System.out.println(getName()+":开始生产产品....");
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.produceProduct();
}
}
}
消费者
public class Consumer extends Thread{
private Clerk clerk;
public Consumer(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run(){
System.out.println(getName()+":开始消费产品......");
while (true){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.consumeProduct();
}
}
}
店员
public class Clerk {
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 consumeProduct(){
if(productCount>0){
System.out.println(Thread.currentThread().getName()+":开始消费第"+productCount+"个产品");
productCount--;
notify();
}else {
try { //等待
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试
public class Test {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer p1 = new Producer(clerk);
p1.setName("生产者1");
Consumer c1 = new Consumer(clerk);
c1.setName("消费者1");
Consumer c2 = new Consumer(clerk);
c2.setName("消费者2");
p1.start();
c1.start();
c2.start();
}
}
标签:Java,Clerk,生产者,clerk,线程,Consumer,public,店员
From: https://www.cnblogs.com/zhishu/p/16900582.html