java經常使用實現延時任務的方式

java開發中常會用到延時任務,主要用到的異步延時任務有TimerTask 和ScheduledExecutorService 兩種方式java

1.使用TimerTask 類實現延時任務

優勢:使用方便簡潔
缺點:若大量使用,會比較消耗資源
Timer timer = new Timer();
        TimerTask timerTask =new TimerTask(){
            @Override
            public void run() {
                System.out.println("TimerTask=====》》》》》延時器");
            }
        };
        timer.schedule(timerTask,1000);//1.任務 2.時間(毫秒)

2.使用 ScheduledExecutorService 延遲任務線程池

優勢:建立一個異步任務池,如有大量異步任務,則推薦使用鏈接池
缺點: 少許異步任務不適合使用
ScheduledExecutorService scheduledExecutorService=new ScheduledThreadPoolExecutor(10);
      scheduledExecutorService.schedule(new Runnable() {
            @Override
      public void run() {
         System.out.println("scheduledExecutorService====>>>延時器");
      }
},1, TimeUnit.SECONDS);//線程實現,二、延遲時間 3.單位
相關文章
相關標籤/搜索