2013-02-04 19 views
1

我想知道如何監視兩個線程,以這種方式,如果一個線程處於等待狀態時間,我想運行另一個線程...在java中監視2個線程,這些線程是基於使用java.util.Timer的時序相互依賴的

要特別在我在做什麼。我有2個線程..作家主題:

writer = new Thread() { 
    public void run() { 
    try { 
     Util.copyStream(remoteInput, localOutput); 
    } catch(IOException e) { 
     e.printStackTrace(); 
     System.exit(1); 
    } 
    } 
}; 

writer.setPriority(Thread.currentThread().getPriority() + 1); 
writer.start(); 
reader.setDaemon(true); 
reader.start(); 

try { 
    writer.join(); 
    reader.interrupt(); 
} catch(InterruptedException e) { 

} 

和讀取器線程:

reader = new Thread() { 
    public void run() { 
    int ch; 
    try { 
     while(!interrupted() && (ch = localInput.read()) != -1) { 
      System.out.print((char)ch); 
      localOutput.write(ch); 
      if (ch==10) { 
       remoteOutput.write(ch); 
       remoteOutput.flush(); 
       sleep(1000); 
       continue; 
      } 
      remoteOutput.write(ch); 
      remoteOutput.flush(); 
      } 
    } catch(Exception e) { 
     e.printStackTrace(); 
    } 
    } 
}; 

所以,如果我寫線程不從「remoteInput」到「localOutput」寫了一個多特定時間例如3秒,我應該「運行」讀取器線程,以便讀取器從「localInput」讀取並寫入「remoteOutput」。 localInput和remoteInput是InputStreams,而remoteInput和remoteOutput是簡單的OutputStreams。我也想知道是否可以使用java.util.Timer 請幫助我通過.. 在此先感謝。

+0

重新格式化請先讓您的代碼正確。 – Andremoniy

回答

0

您可以結合使用wait/notify和Timer類來決定何時觸發通知事件。