2013-08-01 28 views
0

我有myThread.wait()synchronzed(myThread)區塊。我有Myrunner實現可運行。我想告訴myRunner的notify(),但它不是監視器對象。是否有可能從myRunnable處理myThread來進行通知?還有其他解決方案嗎?從Thread擴展myRunnable並運行它是不好的,因爲我的代碼特定相關的一些原因。從可運行通知()

public class ThreadMain { 
    public Thread reader; 
    private class SerialReader implements Runnable { 
     public void run() { 
      while (true) { 
       try { 
        Thread.sleep(3000);     
        synchronized(this) { 
         System.out.println("notifying"); 
         notify(); 
         System.out.println("notifying done"); 
        }     
       } catch (Exception e) { 
        System.out.println(e); 
       }     
      } 
     } 
    } 

    ThreadMain() { 
     reader = new Thread(new SerialReader()); 
    } 

    public static void main(String [] args) { 
     ThreadMain d= new ThreadMain();  
     d.reader.start(); 
     synchronized(d.reader) { 
      try {  
       d.reader.wait(); 
       System.out.println("got notify"); 
      } catch (Exception e) { 
       System.out.println(e); 
      }  
     }   
    } 
} 
+1

顯示你做了什麼。 –

+1

而不是描述你的代碼,複製並粘貼它 - 它會更容易幫助你。 – assylias

+0

我添加了模擬問題的代碼 – vico

回答

0

notify()一個wait() ING線程你多少必須是wait()對對象的引用,你必須能夠在其上獲取鎖。我建議你也改變一個狀態,在wait() ing時通知你並且檢查狀態變化。

唯一的其他選擇是更改等待線程的代碼。