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

Java多线程解决生产者消费者问题

2014-08-30 13:21 288 查看
public class ProducerConsumer {
static final int MAXBUFFER=100;
static Producer producer=new Producer();
static Consumer consumer=new Consumer();
static Monitor monitor=new Monitor();

public static void main(String[] args) {
producer.start();
consumer.start();
}
static class Producer extends Thread{
public void run(){
int item=0;
while(true){
//produceAction()
System.out.println("Producer insert "+item+" into buffer "+monitor.count);
monitor.insert(item);
}
}
}
static class Consumer extends Thread{
public void run(){
int item;
while(true){
item=monitor.remove();
//consumeAction()
System.out.println("Consumer remove "+item+" from buffer "+monitor.count);
}
}
}
//管程
static class Monitor{
int []buffer=new int[MAXBUFFER];
private int count=0,low=0,high=0;

public synchronized void insert(int val){
//if buffer is full,then go to sleep
if(count==MAXBUFFER) goToSleep();
buffer[high]=val;
high=(high+1)%MAXBUFFER;
count++;
//notify consumer
if(count==1) notify();
}
public synchronized int remove(){
int val;
if(count==0) goToSleep();
val=buffer[low];
low=(low+1)%MAXBUFFER;
count--;
if(count==MAXBUFFER-1) notify();
return val;
}

private void goToSleep(){
try{
wait();
} catch (Exception e) {
};
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: