ScheduledExecutorService 源码分析

public interface ScheduledExecutorService extends ExecutorService {

	// 创建在指定延迟后执行且只运行一次的的任务
	public ScheduledFuture<?> schedule(Runnable command,
				       long delay, TimeUnit unit);

	// 同上,这里是callable对象
	public <V> ScheduledFuture<V> schedule(Callable<V> callable,
					   long delay, TimeUnit unit);

	// 创建在初始延迟后执行并周期性调用的的任务
	// 如果执行任务时间大于周期,则下一个任务开始时间会推迟,不会存在并行执行。
	public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
						  long initialDelay,
						  long period,
						  TimeUnit unit);

	// 创建在初始延迟后执行并周期性调用的的任务。
	// 和上面的区别:这里的delay是前一个任务执行完成后,和下一个任务开始时间的间隔。
	public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
						     long initialDelay,
						     long delay,
						     TimeUnit unit);

}



测试:
public class ScheduledExecutorServiceTest {

	private static final int POOL_SIZE = 4;
	
	private static ScheduledExecutorService ses = null;
	
	@org.junit.Before
	public void setUp() {
		ses = Executors.newScheduledThreadPool(POOL_SIZE);
	}
	
	@After
	public void tearDown() {
		ses.shutdown();
	}
	
	@Test
	public void scheduled() throws InterruptedException, ExecutionException {
		MyCall task = new MyCall();
		ScheduledFuture<String> future = ses.schedule(task, 100, TimeUnit.MICROSECONDS); // 延时100+1000毫秒打印
		System.out.println(future.get());
	}
	
	@Test
	public void scheduledAtFixedRateTest() throws InterruptedException, ExecutionException {
		MyCmd cmd = new MyCmd();
		ses.scheduleAtFixedRate(cmd, 100, 2000, TimeUnit.MILLISECONDS); // 首次延迟100毫秒,然后每隔3000毫秒打印
	}
	
	@Test
	public void scheduledAtFixedDelayTest() {
		MyCmd cmd = new MyCmd();
		ses.scheduleWithFixedDelay(cmd, 100, 2000, TimeUnit.MILLISECONDS);  // 首次延迟100毫秒,然后每隔5000毫秒打印
	}

	static class MyCall implements Callable<String> {

		@Override
		public String call() throws Exception {
			TimeUnit.MILLISECONDS.sleep(1000);
			return "MyTask is done";
		}
		
	}
	
	static class MyCmd implements Runnable {

		@Override
		public void run() {
			System.out.println(System.currentTimeMillis());
			System.out.println("MyCmd is done!");
			try {
				TimeUnit.MILLISECONDS.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
}


scheduledAtFixedRateTest输出 (间隔3000毫秒=max(2000, 3000)):
1382933139719
MyCmd is done!
1382933142719
MyCmd is done!

scheduledAtFixedDelayTest输出 (间隔5000毫秒=2000+3000):
1382932484185
MyCmd is done!
1382932489185
MyCmd is done!

你可能感兴趣的:(java,Concurrent,executorService,scheduled)