2013-07-01 166 views
1

我有點惱人的問題。現在,我有一段代碼啓動一個線程,在該線程中設置一個計時器,然後退出該線程並繼續其生命。我的意圖是讓程序在繼續執行代碼流之前等待TimerTask完成。但是,顯然,設置一個新的TimerTask不會暫停執行以等待定時器運行。Java:在繼續執行之前等待TimerTask完成

我該如何設置,以便我的代碼到達TimerTask,等待TimerTask過期,然後繼續?我甚至應該使用計時器嗎?我到處尋找解決方案,但我似乎無法找到一個解決方案。

timer = new Timer(); 
    Thread t = new Thread(new Runnable(){ 
     boolean isRunning = true; 
     public void run() { 
      int delay = 1000; 
      int period = 1000; 
      interval = 10; 
      timerPanel.setText(interval.toString()); 

      //Scheduling the below TimerTask doesn't wait 
      //for the TimerTask to finish before continuing 
      timer.scheduleAtFixedRate(new TimerTask() { 

       public void run() { 
        timerPanel.setText(setInterval().toString()); 
       } 
      }, delay, period); 

      System.out.println("Thread done."); 
     } 
    }); 
    t.start(); 

    try { 
     t.join(); //doesn't work as I wanted 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    endTask(); 

在此先感謝。

編輯:對於重複任務的混淆抱歉。我需要重複這個任務,因爲它是一個倒數計時器,每秒鐘從10變爲0。函數setInterval()最終會取消定時器。下面是相關的代碼:

private final Integer setInterval() { 
    if (interval == 1) 
     timer.cancel(); 
    return --interval; 
} 
+0

您是否試過[Thread.sleep](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long))? –

+0

你已經安排了一個重複的任務,它永遠不會完成。 –

+4

如果你有它的計劃 - 它會重複。如果你不需要重複它,並需要等待,直到它完成 - 你不需要它。只需創建一個方法並調用它 – Tala

回答

0

您應該使用Thread.sleep函數,而不是TimeTask暫停執行。

TimerTask並不意味着停止執行,它就像一個在後臺運行的時鐘。所以對於你的要求你應該去Thread.sleep

+0

問題在於我創建的新線程不斷更新用戶界面。睡覺的主線程的時間量新的線程看起來像一個狡猾的解決方案。 – rkoth

0

使用信號量。在聲明計時器任務之前初始化它,使用0許可證。在計時器任務中,使用try/finally塊釋放信號量。在主線程中,從信號量獲取許可。

在你的代碼中,連接按照指定的方式工作,因爲它等待線程完成。不,使用這個線程是沒有必要的。如果你真的想阻塞一段時間,你不需要一個定時器。獲取當前時間,計算millis直到將來的時間,然後sleep()。

4

我相信CountDownLatch會做你想做的。

final CountDownLatch latch = new CountDownLatch(10); 
int delay = 1000; 
int period = 1000; 

timerPanel.setText(Long.toString(latch.getCount())); 

timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() { 
    public void run() { 
     latch.countDown(); 
     timerPanel.setText(Long.toString(latch.getCount())); 
    } 
}, delay, period); 

try { 
    latch.await(); 
} 
catch (InterruptedException e) { 
    e.printStackTrace(); 
} 

timer.cancel(); 
相關問題