2016-05-14 10 views
-2

は、私が一度に実行されている唯一の1つのスレッドですが、割り当てがwait()を使用して通知するように私を必要としていることを確認しようとしていた)(通知する方法コール。私のコードで は、私は、スレッド(それらの3)の配列を作成し、私はループ内でそれらをすべて開始します。ループでは、スレッドが完了した後、あるスレッドが実行されている間に他のスレッドを待機させようとしましたが、それは他のスレッドに通知します。何らかの理由で が動作しませんでした。私のコードで何が間違っているのか尋ねてもいいですか?正しく)(wait()を使用して、私の割り当てで

 //make array of reservation thread 
     Thread[] reserve = new Thread[3]; 
     for(int i=0; i< reserve.length; i++){ 
      reserve[i] = new Thread(new Reservation(2016, monthArray[i], dayArray[i], hourArray[i])); 

     } 


     for(int i=0; i< reserve.length; i++){ 
      //start first thread 
      reserve[i].start(); 

      //if the thread is running, all other thread should be waiting 
      while(reserve[i].isAlive()){ 
       for(int j=i+1; j<= reserve.length; j++){ 
        try { 
         synchronized(reserve[j]){ 
         reserve[j].wait(); 
         } 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 

       } 
      } 

      //after the previous thread completed, resume other threads 
      reserve[i].notifyAll(); 
     } 

予約の内容

public class Reservation implements Runnable{ 
    public int time; 
    public int day; 
    public int month; 
    public int year; 
    public Reservation (int t, int d, int m, int y){ 
     time= t; 
     day= d; 
     month=m; 
     year= y; 
    } 

    public void run(){ 
     try{ 
      System.out.println("you made reservation at "+day +"/" +month+ "/"+ year +" " + time); 

     } 
     catch(Exception e){ 

      } 
     } 

    public void display(String a){ 
     System.out.println(a); 
    } 
} 
+0

ご予約の内容をご確認ください –

+0

[OracleのJava Webサイトに関する基本チュートリアル](https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html)をお使いになりましたか?コメントのために –

+0

ありがとうございます。私は予約内容を追加しました。私はwait()を使用して通知する方法について、カップルのyoutubeビデオを見ましたが、それらはすべてオブジェクトに実装されています。私はロックと同期の違いを尋ねることができますか? – Kuge4399

答えて

0

開始する第二forのうち最初にreserve[i].start();を移動します。

第二に、あなたの第二forは、あなたのスレッドの体にする必要があります。

+0

ありがとう:私はあなたがそのテーマに関するチュートリアルを読むことをお勧め! reserve [i] .start()を最初のforループに移動すると、ループはすべてのスレッドを開始しませんでしたか? – Kuge4399

+0

それはアイデアです – Lee

関連する問題