码迷,mamicode.com
首页 > 其他好文 > 详细

生产者消费者

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

标签:charles   algo   rac   system   sys   ace   not   new t   syn   

package com.charles.algorithm;

public class ConsumerProducer {
/**
* @desc: single object implements producer and consumer by array
*/
final private int SIZE = 10;
private int head = 0, tag = 0, count = 0;
private Object[] items = new Object[SIZE];

public static void main(String[] args) {

// define 5 producers
ConsumerProducer conducer = new ConsumerProducer();
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
conducer.produce();
}
}
}).start();
}
// define 3 consumers
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
conducer.consume();
}
}
}).start();
}
}

public synchronized void produce() {
while (isFull()) {
try {
System.out.println(Thread.currentThread().getName() + " 已满:" + count +" 等代销费者");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

items[tag++] = true;
count++;
if (tag == items.length) {
tag = 0;
}
this.notifyAll();
try {
System.out.println(Thread.currentThread().getName() + " 生产一个,剩余" + count);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void consume() {
while (isEmpty()) {
try {
System.out.println(Thread.currentThread().getName() + " 已空:" + count+" 等代生产者");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

items[head] = null;
head++;
count--;
if (head == items.length) {
head = 0;
}
this.notifyAll();
try {
System.out.println(Thread.currentThread().getName() + " 消费一个,还有" + count);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private boolean isFull() {
return count == items.length;
}

private boolean isEmpty() {
return 0 == count;
}
}

生产者消费者

标签:charles   algo   rac   system   sys   ace   not   new t   syn   

原文地址:http://www.cnblogs.com/julygift/p/7197047.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!