https://blog.csdn.net/haoxuhong/article/details/79523541
在項目中有很多的方法可能我們不需要立即執行,那麼就需要延時。
首先第一種就是線程: sleep會阻塞線程
new Thread (new Runnable(){
public void run(){
Thread.sleep(time);
method(); //執行的方法
}
})
第二種就是 定時器:
TimerTask task = new TimerTask(){
public void run(){
//method
}
}
Timer timer = new Timer();
timer.schedule(task,delay);
第三種就是: postDelayed不會阻塞線程
new Handler().postDelayed(new Runnable(){
public void run(){
//execute the task
}
},delay);
例如如下代碼:
int i = 0;
long delayMillis = 900000;
while(i<13)
{
hanlder.postDelayed(runnable, delayMillis*i);
i++;
/*此處postDelay不會阻塞線程,這裏的意思是等待delayMillis*i毫秒以後再將線程加入隊列,但是程序後面代碼依然會立即繼續執行,而不是等待delayMillis*i毫秒後再執行。*/
/*剛開始我的理解是程序會在postDelayed處暫停等待 delayMillis*i毫秒後再執行後面的i++,但是經過測試,發現這是錯誤的。實際情況是程序會立即執行i++;所以這裏的執行情況應爲:程序連續執行12次postDelayed,只是會在delayMills*i 毫秒後才依次加入隊列中。*/
第四種是 AlarmManager 一般的簡單任務不這麼做。
---------------------
作者:ailinghao
來源:CSDN
原文:https://blog.csdn.net/haoxuhong/article/details/79523541
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!