生产者消费者

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生产者消费者相关的知识,希望对你有一定的参考价值。

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();
}
}
}

以上是关于生产者消费者的主要内容,如果未能解决你的问题,请参考以下文章

JAVA模拟生产者与消费者实例

生产者消费者问题

Linux生产者消费者模型

Linux生产者消费者模型

生产者消费者模型

生产者消费者模型详解