Java多线程~~~ScheduledThreadPoolExecutor 计划任务类的使用

前面我们已经学习了使用ThreadPoolExecutor类来实现自动创建和运行线程。但是那些线程都是一提交就会运行

,我们有时候希望不要一提交就运行,而是延迟一段时间或者周期性的运行某个任务,这样我们该怎么办呢,下面就介

绍这个类ScheduledThreadPoolExecutor,他就能帮助我们实现这样的效果,代码如下。


package com.bird.concursey.charpet7;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Task implements Callable<String> {
	
	private String name;
	
	public Task(String name) {
		super();
		this.name = name;
	}

	@Override
	public String call() throws Exception {
		System.out.printf("%s: Starting at : %s\n",name,new Date());
		return "hello world";
	}
	
	public static void main(String[] args) {
		ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
		System.out.printf("Main: Starting at: %s\n",new Date());
		for(int i = 0; i < 5; i++) {
			Task task = new Task("Task " + i);
			executor.schedule(task, i, TimeUnit.SECONDS);
		}
		executor.shutdown();
		
		try {
			executor.awaitTermination(1, TimeUnit.DAYS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.printf("Main: Ends at: %s\n",new Date());
	}
}


可以看到运行结果

Main: Starting at: Fri Sep 26 21:59:50 CST 2014
Task 0: Starting at : Fri Sep 26 21:59:50 CST 2014
Task 1: Starting at : Fri Sep 26 21:59:51 CST 2014
Task 2: Starting at : Fri Sep 26 21:59:52 CST 2014
Task 3: Starting at : Fri Sep 26 21:59:53 CST 2014
Task 4: Starting at : Fri Sep 26 21:59:54 CST 2014
Main: Ends at: Fri Sep 26 21:59:54 CST 2014

虽然都是同时提交的任务,dan‘shi

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。