用java实现管程,解决进程互斥问题

来源:互联网 发布:芜湖开淘宝企业店铺 编辑:程序博客网 时间:2024/06/03 19:16
import java.util.*;


public class ProduceConsumer{


static final int N = 2;//define the size of the buffer
static producer p = new producer();//initial a thread of producer
static consumer c = new consumer();//initial a thread of consumer
static our_monitor mon = new our_monitor();//initial a thread of a new pipe


public static void main(String args[]){
p.start();
c.start();
}


static class producer extends Thread{
public void run(){
int item;
while(true){//the loop of a producer
item = produce_item();
mon.insert(item);
}
}
private int produce_item(){
int p=1;
System.out.println("Produce:"+p);
return p;
}
}
static class consumer extends Thread{
public void run(){
int item;
while(true){
item = mon.remove();
consume_item(item);
}
}
private void consume_item(int item){
System.out.println("consumer:"+item);
}
}


static class our_monitor{//a pipe
private int buffer[] = new int[N];
private int count = 0,lo = 0, hi = 0;

public synchronized void insert(int val){
try{

Thread.sleep(500);
}catch(InterruptedException e){
System.out.println("error");
}
if(count == N)go_to_sleep();
buffer[hi] = val;
hi=(hi + 1) % N;
count = count + 1;
if(count == 1)notify();


}


public synchronized int remove(){
try{

Thread.sleep(500);
}catch(InterruptedException e){
System.out.println("error");
}
int val;
if(count == 0)go_to_sleep();
val = buffer[lo];
lo = (lo + 1) % N;
count = count -1;
if(count == N-1)notify();
return val;
}
private void go_to_sleep(){
try{
wait();
}catch(InterruptedException e){
System.out.println("error");
}
}
}


}