###前提・実現したいこと
入門書を参考にしました。
スレッド同士を待ち合わせるプログラムで、
3つのproducerと3つのconsumerが5つのキューで数字を入れ食いするプログラム(見ていただければわかると思います。)を作りたいのですが、どうすれば現在それぞれ2つずつのproducerとconsumerを3つずつランダムに動かせますか?
できれば具体的に教えていただけると助かります。
ご回答よろしくお願いいたします。
###該当のソースコード
java
1package thread; 2 3public class ProducerConsumer { 4 5 public static void main(String[] args) { 6 MyQueue queue = new MyQueue(5); 7 Producer producer = new Producer(queue); 8 Consumer comsumer = new Consumer(queue); 9 producer.start(); 10 comsumer.start(); 11 } 12} 13 14class MyQueue{ 15 int[] intbuf; 16 int start; 17 int count; 18 public MyQueue(int size){ 19 intbuf = new int[size]; 20 start = 0; 21 count = 0; 22 } 23 public synchronized void put(int n) throws InterruptedException{ 24 while(count >= intbuf.length){ 25 System.out.println(Thread.currentThread().getName() +"wait: バッファの空きを待つ"); 26 wait(); 27 } 28 int end = (start + count) % intbuf.length; 29 intbuf[end] = n; 30 count++; 31 notifyAll(); 32 } 33 public synchronized int take() throws InterruptedException{ 34 while(count== 0){ 35 System.out.println(Thread.currentThread().getName() + "wait:データを待つ"); 36 wait(); 37 } 38 int n = intbuf[start]; 39 start = (start+1) % intbuf.length; 40 count--; 41 notifyAll(); 42 return n; 43 } 44} 45class Producer extends Thread{ 46 static final int END = -1; 47 MyQueue queue = null; 48 Producer(MyQueue queue){ 49 this.queue = queue; 50 } 51 public void run(){ 52 try{ 53 for (int i = 1;i<100;i++){ 54 int n = produce(i); 55 queue.put(n); 56 } 57 queue.put(Producer.END); 58 }catch(InterruptedException e){ 59 } 60 } 61 int produce(int n){ 62 sleepRandomly(); 63 System.out.println("Producer:"+Thread.currentThread().getName() +"は"+"を生産完了"); 64 return n; 65 } 66 void sleepRandomly(){ 67 try{ 68 int n = (int)(Math.random()*1000); 69 Thread.sleep(n); 70 }catch (InterruptedException e){ 71 } 72 } 73} 74 75class Consumer extends Thread{ 76 MyQueue queue = null; 77 Consumer(MyQueue queue){ 78 this.queue = queue; 79 } 80 81 public void run(){ 82 try{ 83 while(true){ 84 int n = queue.take(); 85 if(n==Producer.END){ 86 break; 87 } 88 consume(n); 89 } 90 }catch(InterruptedException e){ 91 } 92 } 93 void consume(int n){ 94 System.out.println("consumer:"+Thread.currentThread().getName()+"は"+n+"を消費中"); 95 sleepRandomly(); 96 } 97 void sleepRandomly(){ 98 try{ 99 int n = (int)(Math.random()*1000); 100 Thread.sleep(n); 101 }catch(InterruptedException e){ 102 } 103 } 104} 105
###実行結果
lang
1Thread-1wait:データを待つ 2Producer:Thread-0はを生産完了 3consumer:Thread-1は1を消費中 4Producer:Thread-0はを生産完了 5consumer:Thread-1は2を消費中 6Thread-1wait:データを待つ 7Producer:Thread-0はを生産完了 8consumer:Thread-1は3を消費中 9Producer:Thread-0はを生産完了 10consumer:Thread-1は4を消費中 11Thread-1wait:データを待つ 12Producer:Thread-0はを生産完了 13consumer:Thread-1は5を消費中 14Thread-1wait:データを待つ 15Producer:Thread-0はを生産完了 16consumer:Thread-1は6を消費中 17Thread-1wait:データを待つ 18Producer:Thread-0はを生産完了 19consumer:Thread-1は7を消費中 20Producer:Thread-0はを生産完了 21///
###試したこと
課題に対してアプローチしたことを記載してください
###補足情報(言語/FW/ツール等のバージョンなど)
より詳細な情報