经典例题:生产者/消费者问题
生产者(Productor)将产品放在柜台(Counter),而消费者(Customer)从柜台 处取走产品,生产者一次只能生产固定数量的产品(比如:1), 这时柜台中不能 再放产品,此时生产者应停止生产等待消费者拿走产品,此时生产者唤醒消费者来 取走产品,消费者拿走产品后,唤醒生产者,消费者开始等待.
代码
柜台(Counter)
package com.ffyc.javathread.demo9;
/*
柜台角色 共享数据
*/
public class Counter {
//代表商品数量 初始为0
int num = 0;
//负责生产商品的方法,锁对象是this,add()和sub()用的是同一ba锁
public synchronized void add(){
if(num == 0){
System.out.println("生产者生产了一件商品");
//生产了一件商品
num = 1;
//唤醒消费者线程
this.notify();
}else {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//负责消费商品的方法
public synchronized void sub(){
if(num > 0){
System.out.println("消费者拿走了一件商品");
//消费者拿走了商品
num = 0;
this.notify();
}else {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
生产者(Productor)
package com.ffyc.javathread.demo9;
/*
生产者线程
*/
public class ProductorThread extends Thread{
Counter counter;
public ProductorThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
while (true){
//生产者线程一直生产
counter.add();
}
}
}
消费者(Customer)
package com.ffyc.javathread.demo9;
public class CustomerThread extends Thread{
Counter counter;
public CustomerThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
while (true){
//消费者线程一直消费
counter.sub();
}
}
}
测试
package com.ffyc.javathread.demo9;
public class Test {
public static void main(String[] args) {
//创建的唯一的一个柜台对象
Counter counter = new Counter();
ProductorThread p = new ProductorThread(counter);
CustomerThread c = new CustomerThread(counter);
p.start();
c.start();
}
}