1. 程式人生 > >timer和ScheduledExecutorService延時器與定時器的使用

timer和ScheduledExecutorService延時器與定時器的使用

直接上程式碼:


Timer timer = new Timer();

int interval = 10; //時間間隔 ,毫秒

timer.schedule(new TimerTask(){

   public void run(){

     //邏輯處理程式碼

   }

},interval,interval);
第一個interval是從等待到第一次執行的時間

第二個interval是從第一次到第二次的執行時間

注:Timer不是執行緒安全的 
ScheduledExecutorService service = Executors.newScheduledThreadPool(執行緒數量);
service.schedule(new Runnable(){
        @Override
         public void run() {
              //邏輯程式碼
         }

}, 延時時間, 秒);

ScheduledExecutorService是執行緒安全的,建議使用。