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

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

1、使用ScheduledThreadPoolExecutor类

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

    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay,
                                           TimeUnit unit) {
        if (callable == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture<V> t = decorateTask(callable,
            new ScheduledFutureTask<V>(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<Void>(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<String> {

	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());
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值