線程池執行者在ThreadPoolExecutor的基礎上給咱們提供了延時(delay)執行和週期執行的功能。性能會優於Timer包。java
ThreadPoolExecutor
Executor
ExecutorService
ScheduledExecutorService
AbstractExecutorServiceide
package calvin; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class TestScheduledThreadPoolExecutor { public static ScheduledThreadPoolExecutor executor = null; public static void main(String[] args){ System.out.println("test ScheduledThreadPoolExecutor"); executor = new ScheduledThreadPoolExecutor(5); myTask task = new myTask(); // 2秒後執行,執行後就中止 executor.schedule(task, 2l, TimeUnit.SECONDS); // 5秒後執行,執行完後每10秒再執行不會自動中止 executor.scheduleWithFixedDelay(task, 5l, 10, TimeUnit.SECONDS); } public static class myTask implements Runnable{ public AtomicInteger index = new AtomicInteger(); @Override public void run(){ System.out.println(System.currentTimeMillis() + "start working thread = "+Thread.currentThread().getName() + " index =" + index.incrementAndGet()); } } }