前面我们已经学习了使用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

GitHub 加速计划 / th / ThreadPool
7.74 K
2.22 K
下载
A simple C++11 Thread Pool implementation
最近提交(Master分支:2 个月前 )
9a42ec13 - 9 年前
fcc91415 - 9 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐