2016-08-02 231 views
0

我想讓我的runnable在再次啓動前等待幾秒鐘,關於如何執行此操作的任何建議?Java如何在繼續之前等待

如果我使用this.wait();它不起作用,因爲它在我的程序中停止了運行,我只想讓runnable暫停。

+1

確保您調用運行的螺紋開始 – Sarief

+0

相關:http://stackoverflow.com/questions/11548864/how-to-make-an -android-program-wait – Sufian

+0

試試這個http://stackoverflow.com/questions/15874117/how-to-set-delay-in-android –

回答

0

下面是一個例子2秒延遲Runnable

final Handler handler = new Handler(); 
final Runnable runnable = new Runnable() { 
    @Override 
    public void run() { 
     // Do stuff 

     handler.postDelayed(this, 2000); 
    } 
}; 

handler.postDelayed(runnable, 2000); 
+0

非常感謝你! – Unskilled

0

希望這有助於

Handler handler = new Handler(); 
final Runnable runner = new Runnable() 
{ 
    public void run() 
    { 
    //Restarts  
    handler.postDelayed(this, 1000); 
    } 
}; 

Thread thread = new Thread() 
{ 
@Override 
public void run() { 
    try { 
     while(true) { 
      sleep(1000); 
      handler.post(runner); 
     } 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 
}; 

thread.start(); 
0

這聽起來主線程被阻塞在你的榜樣。看下面的例子。這裏主線程不會被調用wait阻塞。這裏

public void onClick(View v) { 
new Thread(new Runnable() { 
    public void run() { 
     try { 
       synchronized (this) { 
        wait(1000); 
       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
    } 
    }).start(); 
} 

Look是對線程的一個例子: Android.com/processes and threads

相關問題