2016-05-14 81 views
-2

在我的任務中,我試圖確保一次只運行一個線程,但該任務需要我使用wait()和notify()調用。 在我的代碼中,我創建了一個線程數組(其中3個),並且我在一個循環中啓動它們。在循環中,我試圖讓其他線程等待一個線程正在運行,線程完成後,然後通知其他線程。 由於某種原因,我的代碼無法正常工作,請問我的代碼中出現了什麼問題?如何正確使用wait()和notify()

 //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網站上的基礎教程](https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html)? –

+0

感謝您的評論。我添加了預訂的內容。我觀看了幾個關於如何使用wait()和notify的youtube視頻,但它們都是在對象中實現的。我可以問一下鎖之間的區別和同步嗎? – Kuge4399

回答

0

的內容一開始移動reserve[i].start();流出第二for並進入第一。

其次,您的第二個for需要在您的線程的主體。

+0

感謝您的回覆!如果我將reserve [i] .start()移動到第一個for循環,那麼循環將不會啓動所有線程? – Kuge4399

+0

就是這個想法 – Lee

相關問題