자기가 쓴 것도 아니지. 나는 을 보고 그 중의 코드를 보완했다.
public class ProcessAndConsumer {
/**
* @param args
*/
static final int N =100;
static Producer p= new Producer();
static Consumer c= new Consumer();
static Our_monitor mon = new Our_monitor();
public static void main(String[] args) {
// TODO Auto-generated method stub
p.start();
c.start();
}
//
static class Producer extends Thread{
public void run(){
int item;
while(true){
item=producer_item();
mon.insert(item);
}
}
private int producer_item(){
int item;
item=(int)(Math.random()*100+1);
System.out.println(" :"+item);
return item;
}
}
//
static class Consumer extends Thread{
public void run(){
int item;
while(true){
item=mon.remove();
consumer_item(item);
}
}
private void consumer_item(int item){
int i=0;
// ( ) 0,
for(i=0;i<N;i++)
if(item == mon.buffer[i]){
mon.buffer[i]=0;
System.out.println(" "+item); // 0 buffer
break;
}
}
}
//
static class Our_monitor{
private int buffer[] =new int[N];
private int count =0,lo=0,hi=0;
public synchronized void insert(int val){
if(count == N)
go_to_sleep();
buffer[hi]=val;
hi=(hi+1)%N;
count=count+1;
if(count == 1)
notify();
}
public synchronized int remove(){
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 (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}