2011-08-02 25 views
1

我有兩個類。在Class1中,我有一個線程,並且在Class2中,我必須暫停/鎖定該線程,該線程將在登錄後立即啓動。在我的場景中,登錄後(在Class2中實現)之後,線程必須等待更多的額外登錄並從數據庫獲取數據。請讓我知道如何控制來自不同課程的其他課程中的Thread。如何鎖定/暫停在另一個類中運行的線程?

的Class1:

public class Class1{ 
Class2 cls2 = new Class2(); 
cls2.logon(); 
// login which will start the thread in the Class2 as well 
// Please suggest what should be done here 

// DB realated stuff need be done here 
// Have to unlock/resume the thread in Class2 
} 

等級2:

public class Class2{ 
public void receiveMessage(String str){ 
    new StringProcessor(str); 
} 

public class StringProcessor implements Runnable { 
    //do some stuff but have to wait for the DB related stuff in Class1 
} 

public void logon(){ 
    //Will create/logon the connection and the message will be start arriving 
} 

} 

登錄後居然還會有TCP/IP連接接收的消息。 receiveMessage()方法將在消息到達時被調用。但我必須暫停,

乾杯, Sakthi。 S

+0

請你能完成你的代碼示例以使Class1和Class2之間有完全的關係 –

回答

3

有幾種方法。

錯誤的是使用Thread.suspend/resume/destroy,因爲它們已被棄用且容易出現死鎖。

您可以...

  1. 使用的Object.wait,Object.notifyAll實現自己的信令機制。
  2. 使用Semaphore類或java.util.concurrent中任何適合您需要的其他類。
相關問題