用多线程完成生产者消费者模型,生产者生产一个产品就等待消费者消费
使用多线程
public static void main(String
[] args
) {
Shop shop
= new Shop();
ProducerThread pt
= new ProducerThread(shop
);
ConsumerThread ct
= new ConsumerThread(shop
);
pt
.setName("生产者");
ct
.setName("消费者");
pt
.start();
ct
.start();
}
}
class ConsumerThread extends Thread{
Shop shop
;
public ConsumerThread(Shop shop
){
this.shop
= shop
;
}
@Override
public void run() {
for (int i
= 0; i
< 10; i
++) {
try {
shop
.getProduct();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
}
}
class ProducerThread extends Thread{
Shop shop
;
public ProducerThread(Shop shop
){
this.shop
= shop
;
}
@Override
public void run() {
try {
for (int i
= 0; i
< 10; i
++) {
shop
.putProduct(new Phone("小米手机"+(i
+1)));
}
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
}
class Shop{
Phone phone
;
boolean flag
= false;
public synchronized
void putProduct(Phone phone
) throws InterruptedException
{
if (flag
== true){
this.wait();
}
System
.out
.println(Thread
.currentThread().getName()+"生产了"+phone
.name
);
this.phone
= phone
;
flag
= true;
notify();
}
public synchronized
void getProduct() throws InterruptedException
{
if (flag
== false){
this.wait();
}
System
.out
.println(Thread
.currentThread().getName()+"消费了"+phone
.name
);
this.phone
= null;
flag
= false;
this.notify();
}
}
class Phone{
String name
;
public Phone(String name
){
this.name
= name
;
}
打印结果: 生产者生产了小米手机1 消费者消费了小米手机1 生产者生产了小米手机2 消费者消费了小米手机2 生产者生产了小米手机3 消费者消费了小米手机3 生产者生产了小米手机4 消费者消费了小米手机4 生产者生产了小米手机5 消费者消费了小米手机5 生产者生产了小米手机6 消费者消费了小米手机6 生产者生产了小米手机7 消费者消费了小米手机7 生产者生产了小米手机8 消费者消费了小米手机8 生产者生产了小米手机9 消费者消费了小米手机9 生产者生产了小米手机10 消费者消费了小米手机10