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

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

2012-05-13 09:25 429 查看
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
;

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");

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: