首页 > 编程知识 正文

javatimer可调时钟(java计时器timer)

时间:2023-05-03 19:09:36 阅读:76470 作者:4164

//*

*普通的真红

*这是最常见的,我们创建了thread,并一直在while循环中运行它。

用sleep方法达到定时任务的效果。 这样可以快速轻松地实现代码,如下所示:

* @author GT

*

*/

公共类任务1 {

publicstaticvoidmain (字符串[ ] args ) {

//run in a second

最终长时间间隔=1000;

Runnable runnable=new Runnable (

公共void run (}

while (真)。

//----- -代码for task to run

system.out.println('Hello!' );

//----EndsHere

try {

thread.sleep (时间间隔;

} catch (互联互通) )

e .打印堆栈跟踪(;

}

}

}

(;

thread thread=new thread (runnable;

thread.start (;

}

}

import java.util.Timer;

import java.util.TimerTask;

//*

*

*与第一种方法相比,好处1启动和取消任务时,2可以指定第一次运行任务所需的延迟时间

*

在实现时,Timer类可以调度任务,而TimerTask通过run ()方法实现特定任务。 Timer实例可以调度多任务,而且是线程安全的。

调用Timer构造函数时,它将创建可用于调度任务的线程。 代码如下。

*

* @author GT

*

*/

公共类任务2 {

publicstaticvoidmain (字符串[ ] args ) {

TimerTask task=new TimerTask (

@Override

公共void run (}

//task to run goes here

system.out.println('Hello!' );

}

(;

Timer timer=new Timer (;

长延迟=0;

长整型=1* 1000;

//schedulesthetasktoberuninaninterval

timer.scheduleatfixedrate(task,delay,intevalPeriod );

} //end of main

}

import Java.util.concurrent.executors;

import Java.util.concurrent.scheduledexecutorservice;

import Java.util.concurrent.time unit;

//*

*

*

* ScheduledExecutorService是作为并发工具从Java SE5的java.util.concurrent引入的。 这是最理想的定时任务实现方法。

*与前面两种方法相比,有以下好处:

与Timer单线程相比,在线程池中执行任务

* 2灵活设置第一次运行任务delay的时间

* 3为设定执行间隔提供良好的承诺

*

*接下来是实现代码。 此示例在scheduledexecutorservice # scheduleatfixedrate中显示。 通过代码中的参数控制,首次添加了延迟时间。

*

*

* @author GT

*

*/

公共类任务3 {

publicstaticvoidmain (字符串[ ] args ) {

Runnable runnable=new Runnable (

公共void run (}

//task to run goes here

system.out.println('Hello!' );

}

(;

scheduledexecutorserviceservice=executors

. newsinglethreadscheduledexecutor (;

//第二个参数是初次执行的延迟时间,第三个参数是定时执行的间隔时间

服务. scheduleatfixedrate (runnable,10,1,TimeUnit.SECONDS );

}

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。