Java 多线程(PART XX) TimerTask

23 篇文章 0 订阅
23 篇文章 1 订阅

Thread和TimerTask

Thread

这里写图片描述

TimerTask

这是一个任务
这里写图片描述
可以看到他们都实现了Runnable接口.
但是TimerTask是一个abstract类。

TimerTask的主要方法

这里写图片描述
如果想让TimerTask执行任务只需要重写run方法。

Timer

官方API的介绍:
这里写图片描述
这里写图片描述

示例代码:

package timerTest;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

class TaskA extends TimerTask{

    @Override
    public void run() {
        try {
            System.out.println("A begin timer= "+new Date());
            Thread.sleep(2000);//模拟耗时2s
            System.out.println("A   end timer= "+new Date());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
public class Main {

    public static void main(String[] args) {
        System.out.println("当前时间:"+new Date());
        Calendar calendarRef=Calendar.getInstance();
        calendarRef.add(Calendar.SECOND, 10);//十秒之后执行
        Date runDate=calendarRef.getTime();
        System.out.println("计划时间:"+runDate);
        TimerTask task=new TaskA();
        Timer timer=new Timer("myTimer");
        timer.schedule(task, runDate, 4000);//每隔4s执行一次
    }

}

运行结果:

当前时间:Thu Oct 12 12:33:40 GMT+08:00 2017
计划时间:Thu Oct 12 12:33:50 GMT+08:00 2017
A begin timer= Thu Oct 12 12:33:50 GMT+08:00 2017
A   end timer= Thu Oct 12 12:33:52 GMT+08:00 2017
A begin timer= Thu Oct 12 12:33:54 GMT+08:00 2017
A   end timer= Thu Oct 12 12:33:56 GMT+08:00 2017
A begin timer= Thu Oct 12 12:33:58 GMT+08:00 2017
A   end timer= Thu Oct 12 12:34:00 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:02 GMT+08:00 2017
A   end timer= Thu Oct 12 12:34:04 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:06 GMT+08:00 2017
A   end timer= Thu Oct 12 12:34:08 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:10 GMT+08:00 2017
A   end timer= Thu Oct 12 12:34:12 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:14 GMT+08:00 2017
A   end timer= Thu Oct 12 12:34:16 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:18 GMT+08:00 2017
A   end timer= Thu Oct 12 12:34:20 GMT+08:00 2017
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值