Java线程中的计时器
我有一个线程负责执行一些进程。我想让这些处理每3秒进行一次。我使用了下面的代码,但是当线程启动时,什么也没有发生。 我假设当我为计时器定义任务时,它会在时间间隔内自动执行Java线程中的计时器,java,multithreading,timer,Java,Multithreading,Timer,我有一个线程负责执行一些进程。我想让这些处理每3秒进行一次。我使用了下面的代码,但是当线程启动时,什么也没有发生。 我假设当我为计时器定义任务时,它会在时间间隔内自动执行ScheduledTask,但它什么也不做。 我错过了什么 class temperatureUp extends Thread { @Override public void run() { TimerTask increaseTemperature = new TimerTask(){
ScheduledTask
,但它什么也不做。
我错过了什么
class temperatureUp extends Thread
{
@Override
public void run()
{
TimerTask increaseTemperature = new TimerTask(){
public void run() {
try {
//do the processing
} catch (InterruptedException ex) {}
}
};
Timer increaserTimer = new Timer("MyTimer");
increaserTimer.schedule(increaseTemperature, 3000);
}
};
我认为您使用的方法具有签名
计划(TimerTask任务,长延迟)
。所以实际上,您只是延迟了唯一执行的开始时间
要计划它每3秒运行一次,您需要使用此方法计划(TimerTask任务、长延迟、长周期)
,其中第三个参数用于给出周期间隔
您可以参考此处的计时器类定义以提供进一步帮助
为了每三秒做一件事,您应该使用scheduleAtFixedRate(请参阅) 然而,您的代码实际上什么都不做,因为您创建了一个线程,在该线程中,您在线程的运行停止之前启动了一个计时器(没有更多的事情要做)。当定时器(这是一个单次触发)触发时,没有线程可中断(之前运行完成)
代码段中的一些错误:
- 您扩展了
类,这并不是很好的实践线程
- 您在
线程中有一个
?这是没有意义的,因为a计时器
在其自身的计时器
上运行线程
Runnable
see以获取一个简短的示例,但是在您给出的代码段中,我看不到同时需要线程
和计时器
请参阅下面的工作计时器的示例,该计时器每次调用时(每3秒)只会将计数器增加一个:
附录:
我做了一个简短的例子,将线程
合并到混合中。因此,现在TimerTask
只会每3秒增加计数器
,而线程
将在每次检查计数器时显示计数器
s值休眠1秒(它将终止自身和计数器==3
之后的计时器):
Timer
&TimerTask
是传统的
&TimerTask
类现在已打开。要在特定时间运行代码,或要重复运行代码,请使用
引用计时器类Javadoc:
Java 5.0引入了Java.util.concurrent包,其中一个并发实用程序是ScheduledThreadPoolExecutor,它是一个线程池,用于以给定的速率或延迟重复执行任务。它实际上是计时器/TimerTask组合的更通用的替代品,因为它允许多个服务线程,接受各种时间单位,并且不需要子类化TimerTask(只需实现Runnable)。将ScheduledThreadPoolExecutor配置为一个线程使其等效于计时器
执行器框架
在现代Java中,我们使用而不是直接寻址类
将任务定义为或。您可以使用如下所示的紧凑lambda语法。或者可以使用常规语法定义实现Runnable
(或Callable
)接口的类
要求ScheduledExecutorService
对象每隔一段时间执行Runnable
对象的代码
ScheduledExecutorService ScheduledExecutorService=Executors.newSingleThreadScheduledExecutor();
可运行任务=()->{
System.out.println(“在:+Instant.now()做我的事”);
};
长初始延迟=0升;
长周期=3L;
TimeUnit TimeUnit=TimeUnit.SECONDS;
scheduledExecutorService.submit(任务、初始延迟、周期、时间单位);
…
scheduledExecutorService.shutdown();//停止计划中的任何其他任务。
scheduledExecutorService.awaitTermination();//等待所有当前运行的任务完成/失败/取消。
请注意,我们没有直接管理上面代码中的任何线程对象。管理线程是executor服务的工作
小贴士:
- 当不再需要executor服务时,或当应用程序退出时,请始终优雅地关闭executor服务。否则,支持线程池可能会像僵尸一样无限期地继续运行。您确定要创建
temperatureUp
线程并对其调用start()
?这段代码对我来说很好。你为什么要同时使用线程和计时器呢?计时器运行在它自己的线程上。我认为你应该重新考虑你程序的结构。你必须考虑一个全局计时器(不是每个线程)。如果处理时间超过3秒怎么办?你将如何优雅地结束他们?你需要提供更多的信息和更多的代码:)@AljoshaBre我仍然不知道这个代码有什么问题代码>还是什么都没发生@Elham-我以前没有注意到,但是你正在从另一个线程中生成一个新线程?这是一种非常错误的方法。考虑改变结构,以便生成线程并从全局级别进行调度。这里有一个与示例项目的链接,它将帮助您更改您的结构:换句话说,我不能使用计时器来安排由线程完成的一系列操作。对吗?@Elham:TimerTask本身可以称为线程。您只需在run()函数中定义线程功能,就可以开始了。只是不需要扩展Thread类并使代码复杂化。你必须有一个父类,rite?以预定的延迟和间隔从父类生成TimerTask。请务必添加一些退出条件,否则此任务将继续运行,直到WebApp启动。这是一个课堂作业。我需要为这个程序使用thread类。
class temperatureUp extends Thread
{
@Override
public void run()
{
TimerTask increaseTemperature = new TimerTask(){
public void run() {
try {
//do the processing
} catch (InterruptedException ex) {}
}
};
Timer increaserTimer = new Timer("MyTimer");
//start a 3 seconds timer 10ms later
increaserTimer.scheduleAtFixedRate(increaseTemperature, 3000, 10);
while(true) {
//give it some time to see timer triggering
doSomethingMeaningful();
}
}
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("TimerTask executing counter is: " + counter);
counter++;//increments the counter
}
};
Timer timer = new Timer("MyTimer");//create a new Timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//this line starts the timer at the same time its executed
}
}
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
static Timer timer;
public static void main(String[] args) {
//create timer task to increment counter
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
// System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
};
//create thread to print counter value
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
System.out.println("Thread reading counter is: " + counter);
if (counter == 3) {
System.out.println("Counter has reached 3 now will terminate");
timer.cancel();//end the timer
break;//end this loop
}
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
});
timer = new Timer("MyTimer");//create a new timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//start timer in 30ms to increment counter
t.start();//start thread to display counter
}
}
import java.util.Timer;
import java.util.TimerTask;
public class ThreadTimer extends TimerTask{
static int counter = 0;
public static void main(String [] args) {
Timer timer = new Timer("MyTimer");
timer.scheduleAtFixedRate(new ThreadTimer(), 30, 3000);
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
}