Java中定時任務Timer工具類提供了計划任務的實現,但是Timer工具類是以隊列的方式來管理線程的,並不是以線程池的方式,這樣在高並發的情況下,運行效率會有點低。
ScheduleExecutorService 主要作用是將定時任務與線程池結合使用。
ScheduleExecutorService 的父接口是Executor,父類是ThreadPoolExecutor。
看個例子
final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); List<Future<String>> futureList = new ArrayList<Future<String>>(); // 此線程池運行5個線程 for (int i = 0; i < 5; i++) { final int index = i; System.out.println("Thread-" + index + "-add-" + sf.format(new Date())); Future<String> future = executor.schedule(new Callable<String>() { @Override public String call() throws Exception { System.out.println("Thread-" + index + "-begin-" + sf.format(new Date())); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread-" + index + "-end-" + sf.format(new Date())); return "index-" + index; } }, 4L, TimeUnit.SECONDS); // 延遲4秒后執行 futureList.add(future); System.out.println("Thread-" + index + "-add over-" + sf.format(new Date())); } // future.get() 是阻塞執行的,所以獲取值要在線程都啟動之后,再獲取 for (Future<String> future : futureList) { try { System.out.println(future.get()); // 獲取線程返回值 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
使用工廠類產生ScheduleExecutorService有兩個api:Executors.newScheduledThreadPool( int ) 和 Executors.newSingleThreadScheduledExecutor() 。
ScheduleExecutorService 可以運行Callable,也可以運行Runnable,常用api如下:
execute(Runnable command) 直接執行,執
行命令所需的延遲為零
getQueue() 返回
BlockingQueue<Runnable> 返回此執行器使用的任務隊列
schedule(Callable<V> callable, long delay, TimeUnit unit) 創建並執行給定延遲后啟用的計划任務
schedule(Runnable command, long delay, TimeUnit unit) 創建並執行給定延遲后啟用的計划任務
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 創建並執行一個周期性操作,該操作首先在給定的初始延遲之后啟用,然后以給定的周期啟用
scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) 創建並執行周期性動作,主要左右那個是設置多個任務之間固定的運行時間間隔。
shutdown() 啟動一個有序的關閉,其中先前提交的任務被執行,但是沒有新任務被接受
shutdownNow() 嘗試停止所有積極執行任務,停止等待任務的處理,並返回等待執行的任務的列表
submit(Callable<T> task) 提交一個返回值的任務用於執行