ScheduledExecutorService
我们需要定期或在特定延迟后执行任务,Java提供了Timer类,通过它我们可以实现这一点,但有时我们需要并行运行类似的任务。所以创建多个Timer对象将是系统的开销,最好有一个调度任务的线程池。Java通过ScheduledThreadPoolExecutor类提供计划的线程池实现,实现ScheduledExecutorService接口。
public class WorkerThread implements Runnable{ private String command; public WorkerThread(String s){ this.command=s; } @Override public void run() { System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date()); processCommand(); System.out.println(Thread.currentThread().getName()+" End. Time = "+new Date()); } private void processCommand() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString(){ return this.command; } }
public class ScheduledThreadPool { public static void main(String[] args) throws InterruptedException { ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); //schedule to run after sometime System.out.println("Current Time = "+new Date()); for(int i=0; i<3; i++){ Thread.sleep(1000); WorkerThread worker = new WorkerThread("do heavy processing"); scheduledThreadPool.schedule(worker, 10, TimeUnit.SECONDS); } //add some delay to let some threads spawn by scheduler Thread.sleep(30000); scheduledThreadPool.shutdown(); while(!scheduledThreadPool.isTerminated()){ //wait for all tasks to finish } System.out.println("Finished all threads"); } }
浙公网安备 33010602011771号