2012-01-04 30 views
2

我需要在特定時間段後更新UI,爲此我創建了一個計時器計劃並在其中調用runOnUiThread。如何讓計時器任務等待runOnUiThread完成

timer.scheduleAtFixedRate(new TimerTask() { 

      public void run() { 
       System.out.println("1"); 
        try { 

        System.out.println("2"); 
        System.out.println("3"); 

        runOnUiThread(new Runnable() { 

         public void run() { 
          System.out.println("4"); 
          System.out.println("5"); 
          System.out.println("6"); 
          System.out.println("7"); 
         } 
        }); 

        System.out.println("8"); 
       } catch (Exception e) { 

        e.printStackTrace(); 
       } 

      } 

     }, delay, period); 
     System.out.println("9"); 

我有問題,達成後「3」,計時器線程跳躍到「8」,並且UI線程從「4」運行之後。 我想使計時器線程等待直到UI線程在「7」完成其工作,只有它應該移動到「8」。

樣本輸出

01-05 00:30:16.308: I/System.out(1394): 1 
01-05 00:30:16.308: I/System.out(1394): 2 
01-05 00:30:16.308: I/System.out(1394): 3 
01-05 00:30:16.308: I/System.out(1394): 8 
01-05 00:30:16.308: I/System.out(1394): 4 
01-05 00:30:16.308: I/System.out(1394): 5 
01-05 00:30:16.308: I/System.out(1394): 6 
01-05 00:30:16.308: I/System.out(1394): 7 
01-05 00:30:17.307: I/System.out(1394): 1 
01-05 00:30:17.307: I/System.out(1394): 2 
01-05 00:30:17.307: I/System.out(1394): 3 
01-05 00:30:17.307: I/System.out(1394): 8 
01-05 00:30:17.307: I/System.out(1394): 4 
01-05 00:30:17.323: I/System.out(1394): 5 
01-05 00:30:17.323: I/System.out(1394): 6 
01-05 00:30:17.323: I/System.out(1394): 7 

回答

3

試試這個

Object lock=new Object(); 
timer.scheduleAtFixedRate(new TimerTask() { 

     public void run() { 
      System.out.println("1"); 
       try { 

       System.out.println("2"); 
       System.out.println("3"); 

       runOnUiThread(new Runnable() { 

        public void run() { 
         System.out.println("4"); 
         System.out.println("5"); 
         System.out.println("6"); 
         System.out.println("7"); 
         synchronized(lock){lock.notify();} 
        } 
       }); 
       try{ 
        synchronized(lock){lock.wait();} 
       }catch(InterruptedException x){} 
       System.out.println("8"); 
      } catch (Exception e) { 

       e.printStackTrace(); 
      } 

     } 

    }, delay, period); 
    System.out.println("9"); 
+0

在等待之前發生通知的可能性很小。我寧願在這裏使用倒數計時器。 (或在同步塊中包含runonuithread調用以確保在等待之前不會調用notify) – njzk2 2014-08-20 18:10:01

1

我認爲,實現這一目標是使用 「CountDownLatch」 最簡單的方法。

final CountDownLatch latch = new CountDownLatch(1); 
runOnUiThread(new Runnable() { 
    @Override 
    public void run() { 

     // Do something on the UI thread 

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

// Now do something on the original thread