您的位置:首页 > 编程语言 > Java开发

Java多线程之线程间通信--生产者/消费者模式

2017-08-27 16:01 711 查看
  等待(wait)/通知(notify)模式最经典的案例就是“生产者/消费者”模式。虽然此模式在使用上有几种“变形”,还有一些小的注意事项,但原理都是基于wait/notify的。

public class Storage {
//仓库最大存储量
private final int MAX_SIZE = 10;
// 仓库存储的载体
private LinkedList<Object> list = new LinkedList<Object>();

// 生产num个产品
public void produce() {
// 同步代码段
synchronized (list) {
// 如果仓库剩余容量不足
while (list.size()  ==  MAX_SIZE) {
System.out.println("【库存量】:" + list.size() + "已经达到最大,暂时不能执行生产任务!");
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

list.add(new Object());

System.out.println( "生产一个产品,/t【现仓储量为】:" + list.size());

list.notifyAll();
}
}

// 消费num个产品
public void consume() {
// 同步代码段
synchronized (list) {
// 如果仓库存储量不足
while (list.size() == 0) {
System.out.println("/t【库存量】:" + list.size() + ",暂时不能执行消费任务!");

try {
// 由于条件不满足,消费阻塞
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

list.remove();
System.out.println( "消费一个产品,/t【现仓储量为】:" + list.size());

list.notifyAll();
}
}

}


public class Producer extends Thread {
private Storage storage;

// 构造函数,设置仓库
public Producer(Storage storage) {
this.storage = storage;
}

public void run() {
for(int i = 0; i < 100; i++) {
storage.produce();
}
}

}


public class Consumer extends Thread {
private Storage storage;

// 构造函数,设置仓库
public Consumer(Storage storage) {
this.storage = storage;
}

public void run() {
for(int i = 0; i < 100; i++) {
storage.consume();
}
}
}


public class Test {
public static void main(String[] args) {
Storage storage = new Storage();

Producer producer = new Producer(storage);
producer.start();

Consumer consumer = new Consumer(storage);
consumer.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐