定时器在Java线程(Timer in Java Thread)

2019-06-26 15:07发布

我有一个线程是负责做一些过程。 我想使它让这些处理会每3秒钟内完成。 我用下面的代码,但线程启动时,没有任何反应。 我认为,当我定义了一个任务,我的计时器会自动执行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);

    }
};

Answer 1:

在你的代码的一些错误片段:

  • 您扩展Thread类,它是不是真的好习惯
  • 你有一个Timer一个内Thread ? 这没有道理作为一个Timer自身运行的Thread

你应该相当(当/如果需要),实现Runnable看到这里的一个小例子,但我不能看到一个都需要ThreadTimer在你给的代码片段。

请参阅工作的下面的示例Timer ,这将只是一个在每次调用(每3秒)时,计数器增加:

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只会增加counter由每3秒, Thread将显示counter的价值睡在每次检查计数器(它会自行终止后,定时器时间1秒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
    }
}


Answer 2:

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

}


Answer 3:

为了做一些事情,你应该使用scheduleAtFixedRate每三秒钟(见的javadoc )。

但是你的代码确实没有什么,因为你创建用于启动线程的运行结束之前计时器的线程(没有什么更多的事情要做)。 当计时器(这是一个拍一个)触发,没有线程中断(运行完成之前)。

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


Answer 4:

我想你已经使用的方法有签名schedule(TimerTask task, long delay) 。 所以,实际上你只是延迟只有在执行的起始时间。

要安排它每3秒,你需要去用这种方法运行schedule(TimerTask task, long delay, long period) ,其中第三参数是用来给的周期间隔。

你可以在这里参考Timer类定义为提供进一步的帮助

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html



文章来源: Timer in Java Thread