2011-04-05 76 views
0

我指的是http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/AlarmService_Service.html的Android alarmmanager同步

有可運行的線程看起來像這樣

Runnable mTask = new Runnable() 
{   
    public void run() 
    { 
     Log.v("service", "thread is running after 5 min"); 
     // Normally we would do some work here... for our sample, we will   
     // just sleep for 30 seconds.    
     long endTime = System.currentTimeMillis() + 15*1000;    
     while (System.currentTimeMillis() < endTime) 
     {     
      synchronized (mBinder) 
      {      
       try 
       {       
        mBinder.wait(endTime - System.currentTimeMillis());  
       } 
       catch (Exception e) 
       {      

       }     
      }    
     }   // Done with our work... stop the service!    
     AlarmService_Service.this.stopSelf();  
    }  
} 

我承認我有一些問題與同步的概念...線程運行while循環等待15s,在那個循環中,我等待15s。那麼,如果我只想寫一個日誌條目,runnable如何呢? Log.v(TAG,TEXT);?如果我想在自己的數據庫表中寫入新條目,會發生什麼變化?

感謝,A

回答

0

如果你只是想要一個日誌語句那麼下面將正常工作

Runnable mTask = new Runnable() 
{   
    public void run() 
    { 
     Log.v("TAG", "Some verbose log message"); 
    }  
} 

無論您需要在對象上使用​​取決於對象是否是線程安全與否。如果它不是線程安全的,那麼您將需要確保一次只有一個線程通過使用同步塊來訪問該對象。在你的例子中,mBinder不是線程安全的,所以爲了調用binder的wait方法,你需要確保你是唯一訪問它的線程。

A runnable最常用於在不同線程中執行代碼,因此長時間運行的操作(例如IO,但在這種情況下只是在等待)不會阻塞UI線程。

0

只需更換

嘗試 {
mBinder.wait(結束時間 - System.currentTimeMillis的());
} 趕上(例外五){

}

...你要執行的代碼?

同步只是斷言只有一個進程訪問線程在同一時間。

+0

是和否,我有外部while循環我不需要,那麼我有代碼在裏面的同步(mBinder)。在上面的例子中,他們用mBinder對象做了一些事情(調用wait)。我不會對mBinder對象做任何事情,對嗎?那麼我需要這個同步嗎? – AndyAndroid 2011-04-05 13:05:54