public class ProducerConsumer{ public static void main(String[] args){ Buffer buffer=new Buffer(3); Producer producer=new Producer(buffer); Consumer consumer=new Consumer(buffer); producer.start(); consumer.start(); } } class Buffer{ int[] intbuf; int start; int count; public Buffer(int size){ intbuf=new int[size]; start=0; count=0; } public synchronized void append(int n){ while(count>=intbuf.length){ System.out.println(Thread.currentThread().getName()+" wait:バッファの空きを待つ"); try{ wait(); }catch(InterruptedException e){ System.out.println(e); } } int end=(start+count)%intbuf.length; intbuf[end]=n; count++; notifyAll(); } public synchronized int remove(){ while(count==0){ System.out.println(Thread.currentThread().getName()+" wait:データを待つ"); try{ wait(); }catch(InterruptedException e){ System.out.println(e); } } int n=intbuf[start]; start=(start+1)%intbuf.length; count--; notifyAll(); return n; } } class Producer extends Thread{ Buffer buffer=null; public Producer(Buffer buffer){ this.buffer=buffer; } public void run(){ for(int i=0;i<10;i++){ int n=produce(i); buffer.append(i); } buffer.append(-1); } private int produce(int n){ sleep_randomly(); System.out.println("Producer: "+getName()+" は "+n+" を生産完了"); return n; } public void sleep_randomly(){ try{ int n=(int)(Math.random()*10000); Thread.sleep(n); }catch(InterruptedException e){ System.out.println(e); } } } class Consumer extends Thread{ Buffer buffer=null; public Consumer(Buffer buffer){ this.buffer=buffer; } public void run(){ while(true){ int n=buffer.remove(); if(n==-1){ break; } consume(n); } } private int consume(int n){ System.out.println("Consume: "+getName()+" は "+n+" を消費中"); sleep_randomly(); return n; } public void sleep_randomly(){ try{ int n=(int)(Math.random()*10000); Thread.sleep(n); }catch(InterruptedException e){ System.out.println(e); } } }