2014-04-23 102 views
0

我想在一個Worker線程內定義一個Timer線程,如果Worker線程睡眠時間過長,這將調用Worker線程的中斷方法(該休眠時間是動態定義的)。因此,在本質的代碼將如下所示:使用從線程喚醒睡眠主線程

public class Worker implements Runnable { 
    private Timer timer;   
    @Override 
    public void run(){ 
     try { 
      Thread.sleep(7000); 
      timer.start() 
      //timer must call this Thread's 
      //interrupt method if it sleeps 
      //for more than a specified time. 
     } catch (InterruptedException e) { 
      System.out.println("I was awakened. Gotta work!") 
     } 

    } 
} 

而且這可能是Timer類實現的:

public class Timer implements Runnable { 


    @Override 
    public void run(){ 
     try { 
      Thread.sleep(3000); 
      //Interrupt the parent thread it was called from.. 
      //In this case, an instance of Worker. 
     } catch (InterruptedException e) { 
      System.exit(1); 
     } 

    } 
} 

我不知道我已經找到一種方法來實現這一功能。任何幫助將非常感激!

回答

0

我有幾個輸入,

在類定時器你需要有一流的工人的實例,這樣就可以調用parent.interrupt()。

這樣做的,我建議你創建的定時器類象下面這樣一個新的構造,

public class Timer implements Runnable { 

    Worker parent; 

    public Timer(Worker parent) 
    { 
     this.parent = parent; 
    } 

    @Override 
    public void run(){ 
     try { 
      Thread.sleep(3000); 
      //Interrupt the parent thread it was called from.. 
      //In this case, an instance of Worker. 
      parent.interrupt(); 
     } catch (InterruptedException e) { 
      System.exit(1); 
     } 

    } 
} 

其次,在你類,你需要的順序更改爲以下,

timer.start() 
Thread.sleep(7000); 

否則,您的工作線程將在啓動計時器線程之前休眠。

我希望它有助於..

+0

我已經試過了......,但parent.interrupt()顯示爲syntatically正確。另外,我在Worker類中添加了一個調用「thread.interrupt()」的interrupt()方法,但都無濟於事。無論如何,我找到了解決辦法。感謝您嘗試不管。 –