2012-01-01 95 views
-2

我被綁定以導致對象等待一段時間。在此期間,該對象可能被鎖定,無法處理任何命令。在等待期間,等待活動可能會被取消。如何讓對象等待幾毫秒,然後在等待時間內取消主動等待?

首先,我嘗試以下方法,這是一個簡單的方法:

public void toWaiting(int waitingTime) 
{ 
    synchronized(this) // this is the reference for the current object 
    { 
     try { 
      this.wait(waitingTime); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
    } 
} 

它的工作原理,目前的對象可以被阻止等待,而是在等待期間,我無法取消此等待活動。

所以我試圖用線程來處理這個問題。將等待方法放在一個線程中,然後通過調用Thread.interrupt()取消等待活動。我已經寫了下面的代碼:

public void toWaiting(int waitingTime) 
{ 
    robotWaitTask waitingTask = new robotWaitTask(waitingTime); 
    waitingTask.start(); 
} 

// Generate a thread which could cause the object waiting for a interval 
class robotWaitTask extends Thread 
{ 
    int waitingTime; 

    public robotWaitTask(int waitingTime) 
    { 
     this.waitingTime = waitingTime; 
    } 

    public void run() 
    { 
     synchronized(this) 
     { 
      try { 
       this.wait(waitingTime); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

以上不工作,因爲當前對象不堵塞,除非我改變waitingTask.start()waitingTask.run()(我不知道爲什麼,沒有例外)。我知道調用run方法不會導致產生一個新的線程,它只是一個直接調用。所以如果我使用waitingTask.run(),那麼沒有線程可以被interrupt()方法取消。

如何解決我的問題?

+0

你在哪裏打電話waitingTask.interrupt()? – Tudor 2012-01-01 21:28:49

+2

你並沒有像你應該那樣使用等待,而中斷並不是要喚醒線程,而是要阻止它。閱讀tutorial abount concurrency:http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html。等待方法的javadoc也有有用的信息:http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#wait%28long%29 – 2012-01-01 21:32:01

+0

@Tudor我只是寫一個新的方法來調用waitingTask.interrupt(),當然,我必須將waitingTask實例更改爲全局變量。但第一個問題是waitingTask.start()不起作用。 – 2012-01-01 21:34:18

回答

0

你的代碼應該工作。你說當前對象不會被阻塞,除非你改變使用.run()。如果調用.run(),那意味着該方法在當前線程中執行,而不是單獨的線程。這可能就是爲什麼你「注意到」它阻止了。 如果使用.start(),將創建一個單獨的線程,並在該單獨的線程中阻止該對象。同時,您的主線程將繼續執行。

robotWaitTask waitingTask = new robotWaitTask(1000); 
waitingTask.start(); //start a new thread, and the object is blocked in a separate thread 
//this line will print as soon as the previous line called even before 1000ms 
System.out.println("here)"; 


robotWaitTask waitingTask = new robotWaitTask(1000); 
waitingTask.run(); 
//this line will print after 1000ms because the object is blocked in this thread 
System.out.println("here)"; 
+0

謝謝你的回答!你是對的,我阻止主線程,然後我認爲當前對象被阻塞... – 2012-01-01 23:42:33