Java线程中的定时器 [英] Timer in Java Thread

查看:19
本文介绍了Java线程中的定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程负责执行一些过程.我想让它每 3 秒完成一次这些处理.我使用了下面的代码,但是当线程启动时,什么也没有发生.我假设当我为我的计时器定义任务时,它会在时间间隔内自动执行 ScheduledTask 但它根本不做任何事情.我错过了什么?

I have a thread which is in charge of doing some processes. I want make it so that these processing would be done every 3 seconds. I've used the code below but when the thread starts, nothing happens. I assumed that when I define a task for my timer it automatically execute the ScheduledTask within time interval but it doesn't do anything at all. What am I missing?

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);

    }
};

推荐答案

代码片段中的一些错误:

A few errors in your code snippet:

  • 您扩展了 Thread 类,这不是一个很好的做法
  • 您在 Thread 中有一个 Timer 吗?这是没有意义的,因为 Timer 在它自己的 Thread 上运行.
  • You extend the Thread class, which is not really good practice
  • You have a Timer within a Thread? That doesnt make sense as the a Timer runs on its own Thread.

您应该(在必要时/在必要时)实施 Runnable 参见 这里是一个简短的例子,但是我看不到在您提供的代码段中同时需要 ThreadTimer .

You should rather (when/where necessary), implement a Runnable see here for a short example, however I cannot see the need for both a Thread and Timer in the snippet you gave.

请参阅下面的 Timer 工作示例,它会在每次调用时(每 3 秒)简单地将计数器加一:

Please see the below example of a working Timer which will simply increment the counter by one each time it is called (every 3seconds):

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
    }
}

附录:

我做了一个将 Thread 合并到混合中的简短示例.所以现在 TimerTask 只会每 3 秒将 counter 增加 1,而 Thread 将显示 counter 的值每次检查计数器时休眠 1 秒(它会在 counter==3 之后终止自身和定时器):

I did a short example of incorporating a Thread into the mix. So now the TimerTask will merely increment counter by 1 every 3 seconds, and the Thread will display counters value sleeping for 1 seconds every time it checks counter (it will terminate itself and the timer after counter==3):

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
    }
}

这篇关于Java线程中的定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆