Java并发编程-19-在执行器中延时执行任务和周期性执行任务

一、在执行器中延时执行任务

1、使用ScheduledThreadPoolExecutor类

2、schedule()方法 接收Callable对象或者Runnable对象

    public  ScheduledFuture schedule(Callable callable,
                                           long delay,
                                           TimeUnit unit) {
        if (callable == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture t = decorateTask(callable,
            new ScheduledFutureTask(callable,
                                       triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }

也支持Runnable接口的对象

    public ScheduledFuture schedule(Runnable command,
                                       long delay,
                                       TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture t = decorateTask(command,
            new ScheduledFutureTask(command, null,
                                          triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }


测试代码

package com.concurrency.executor;

import java.util.Date;
import java.util.concurrent.Callable;

public class Task implements Callable {

	private String name;

	public Task(String name) {
		this.name = name;
	}

	@Override
	public String call() throws Exception {
		System.out.printf("%s : Starting at : %s\n", name, new Date());
		return "Hello World !";
	}
}

public void testTask() {

		ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) Executors
				.newScheduledThreadPool(1);

		System.out.printf("Main : Starting at : %s\n", new Date());

		/**
		 * 初始化五个任务,通过schedule()方法启动这些任务
		 */
		for (int i = 0; i < 5; i++) {
			Task task = new Task("Task " + i);
			scheduledThreadPoolExecutor.schedule(task, i + 1, TimeUnit.SECONDS);
			
			
		}

		// 结束执行器
		scheduledThreadPoolExecutor.shutdown();

		// 等待所有的任务结束
		try {
			scheduledThreadPoolExecutor.awaitTermination(1, TimeUnit.DAYS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.println("Mian : Ends at :" + new Date());
	}

二、在执行器中周期性执行任务

    public ScheduledFuture scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);

这个方法只支持Runnable 对象,第三个参数表示任务两次执行开始的时间的间隔

    public ScheduledFuture scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);

这个方法的第三个参数是表示任务上一次执行结束的时间与任务下一次开始执行的时间的间隔


package com.concurrency.executor;

import java.util.Date;

public class Task1 implements Runnable {

	private String name;

	public Task1(String name) {
		this.name = name;
	}

	@Override
	public void run() {
		System.out.printf("%s : Starting at : %s\n", name, new Date());
	}
	
}

public void testTask1() {
		
		//创建工厂类的newScheduledThreadPool执行器对象
		ScheduledExecutorService scheduledExecutorService = Executors
				.newScheduledThreadPool(1);
		System.out.println("Main : Starting at : " + new Date());
		Task1 task = new Task1("Task");

		//scheduleAtFixedRate()这个方法将任务发送给执行器
		//参数分别是:Runnable对象,初始延迟,任务两次执行开始时间的间隔
		//返回一个用来控制任务状态的ScheduledFuture对象
		ScheduledFuture result = scheduledExecutorService
				.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);

		for (int i = 0; i < 10; i++) {
			System.out.println("Main : Delay : "
					+ result.getDelay(TimeUnit.MILLISECONDS));
			try {
				TimeUnit.MILLISECONDS.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		scheduledExecutorService.shutdown();

		//休眠5秒,等待周期性的任务全部执行完成
		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.println("Mian : Finished at " + new Date());
	}


你可能感兴趣的:(Java,并发编程,Java并发编程)