首页 > 其他 > 详细

生产者消费者(二)

时间:2017-07-17 21:09:54      阅读:284      评论:0      收藏:0      [点我收藏+]

package com.charles.algorithm;

import java.util.LinkedList;

public class ProducerConsumer {

/**
* @Desc: multiple sub-classes implements producer and consumer by a list
*/
static final int MAX_SIZE = 10;
LinkedList<Integer> list = new LinkedList<Integer>();

public static void main(String[] args) {

ProducerConsumer pc = new ProducerConsumer();
Consumer consumer = pc.new Consumer();
Producer producer = pc.new Producer();

//define 4 producers
for(int i=0; i<MAX_SIZE/3+1; i++){
new Thread(producer).start();
}
//define 3 consumers
for(int i=0; i<MAX_SIZE/3; i++){
new Thread(consumer).start();
}

}
class Producer implements Runnable {
@Override
public void run() {
while (true) {
produce();
}
}
private void produce() {
synchronized (list) {
while (MAX_SIZE <= list.size()) {
try {
System.out.println("Producer " + Thread.currentThread().getName() + " Waiting...");
list.wait();

} catch (InterruptedException e) {
e.printStackTrace();
}
}
sleep();
list.add(list.size() + 1);
list.notifyAll();
System.out
.println("生产者" + Thread.currentThread().getName() + "生产:" + list.size() + " 剩余: " + list.size());
}
}

}

class Consumer implements Runnable {
@Override
public void run() {
while (true) {
consume();
}
}
private void consume() {
synchronized (list) {
while (0 >= list.size()) {
try {
System.out.println("Consumer " + Thread.currentThread().getName() + " Waiting...");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sleep();
int num = list.pollLast();
System.out.println("消费者" + Thread.currentThread().getName() + "消费:" + num + " 剩余: " + list.size());
list.notifyAll();
}

}

}
private void sleep() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

生产者消费者(二)

原文:http://www.cnblogs.com/julygift/p/7197425.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!