经典的生产者消费者模型(一)

来源:互联网 发布:jquery placeholder.js 编辑:程序博客网 时间:2024/05/22 11:32
package com.zzj.concurrency;import java.util.LinkedList;public class ProducerConsumerModel {private final LinkedList<String> queue = new LinkedList<>(); private final int max = 3;public synchronized void put(String e) {while(queue.size() == max){ // 此处不能用if判断try {wait();} catch (InterruptedException e1) {e1.printStackTrace();}}queue.add(e);notifyAll(); // 通知消费者消费}public synchronized String get(){while(queue.size() == 0){ // 此处不能用if判断try {wait();} catch (InterruptedException e) {e.printStackTrace();}}String r = queue.removeFirst();notifyAll(); // 通知生产者生产return r;}public static void main(String[] args) {final ProducerConsumerModel model = new ProducerConsumerModel();// 启动5生产者for (int i = 0; i < 5; i++) {new Thread(new Runnable() {public void run() {for(int j = 0; j < 10; j++){model.put(Thread.currentThread().getName() + "-" + j);}}}, "producer-" + i).start();}// 启动10消费者for (int i = 0; i < 10; i++) {new Thread(new Runnable() {public void run() {for(int j = 0; j < 5; j++){System.out.println(model.get());}}}, "consumer-" + i).start();}}}

输出:

producer-0-0producer-0-1producer-4-0producer-0-2producer-1-0producer-1-1producer-1-2producer-0-3producer-0-4producer-1-4producer-1-3producer-0-5producer-2-0producer-2-1producer-3-0producer-1-5producer-1-6producer-1-7producer-4-1producer-2-2producer-4-2producer-0-6producer-0-7producer-0-8producer-0-9producer-1-8producer-3-1producer-1-9producer-3-2producer-2-4producer-2-5producer-3-7producer-2-6producer-2-3producer-2-7producer-4-3producer-3-4producer-3-3producer-3-8producer-4-4producer-4-5producer-2-9producer-3-9producer-4-6producer-2-8producer-4-7producer-3-6producer-4-8producer-3-5producer-4-9



阅读全文
0 0
原创粉丝点击