Java多线程(9) 定时线程任务

概述

在上一章中写到执行器的后2个方法是预定执行或重复执行而设计的方法,这是一种允许使用线程池机制的java.util.Timer的泛化。
部分API详解

java.util.concurrent.Executors

ScheduledExecutorService newScheduledThreadPool(int threads)
// 返回一个线程池,他使用给定的线程数来调度任务
ScheduledExecutorService newSingleThreadScheduledExecutor()
// 返回一个执行器,他在一个单独线程中调度任务


java.util.concurrent.ScheduledExecutorService

ScheduledFuture<V> schedule(Callable<V> task,long time,TimeUnit unit)
ScheduledFuture<?> schedule(Runnable task,long time,TimeUnit unit)
// 预定在指定的事件后执行任务
ScheduledFuture<?> scheduleAtFixedRate(Runnable task,long initialDelay, long period, TimeUnit unit)
// 预定在初始的延迟结束后,周期性地运行给定的任务,周期长度是period
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long delay,TimeUnit unit)
// 预定在初始的延迟结束后周期性的给定任务,在一次调用完成和下一次调用开始之间有长度为delay的延迟

我写了一个每隔100毫秒就输出一次当前时间的范例供参考:

package com.utopia.scheduledThreadPool;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadTest {
    @SuppressWarnings("unused")
    public static void main(String args[]) {
        ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
        ScheduledFuture<?> scheduledFuture = pool.scheduleAtFixedRate(new TimeClocker(), 0, 100, TimeUnit.MILLISECONDS);
    }

}
package com.utopia.scheduledThreadPool;

import java.text.SimpleDateFormat;

public class TimeClocker implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        System.out.println("Time:" + sdf.format(System.currentTimeMillis()) + "." + System.currentTimeMillis() % 1000);
    }

}

部分运行截图:
运行截图
这是程序运行的一小部分截图,有一些小小的误差,很正常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值