java Java库 - 定时器和TimerTask

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Java库 - 定时器和TimerTask相关的知识,希望对你有一定的参考价值。

package me.illuminatiproductions;

import java.util.Timer;
import java.util.TimerTask;

//The class that represents our task
class EatPeopleTask extends TimerTask{
    public void run(){
        System.out.println("*eat all the people*");
        System.out.println("End of task.");
    }
}

public class Main {

    public static void main(String[] args) {

        EatPeopleTask task = new EatPeopleTask();
        Timer timer = new Timer();

        timer.schedule(task, 5000); //Executes task 5 seconds after the program starts

        //remember, the timer is a thread that is running concurrent with the main thread of the program
        try{
            Thread.sleep(5000); //After the timer starts, pause the main thread for 5 seconds
        }catch (InterruptedException exc){ }

        timer.cancel(); //then end the program because the thread
        // is done so there is nothing else to do

    }
}

以上是关于java Java库 - 定时器和TimerTask的主要内容,如果未能解决你的问题,请参考以下文章

Spring定时任务的几种实现

java Java库 - 定时器和TimerTask

[java两个数据库同步]Java代码之JDBC实现数据库之间定时的表格传输(由一个库读取到另一个库)实例

多线程_高级主题_定时调度

Java多线程与并发库高级应用-传统定时器技术回顾

(黑马Java多线程与并发库高级应用)02 传统定时器技术回顾