【问题标题】:Running a Timer From Within a Java Thread从 Java 线程中运行计时器
【发布时间】:2014-01-30 12:31:46
【问题描述】:

我会链接以每 5 秒从我的线程中执行一个方法。我的课堂大纲如下。

private static Timer timer = new Timer();

public class myThread implements Runnable {

    public void run() {

        //listens for incoming messages
        while(true) {

            //process queue
            timer.schedule(new TimerTask() {
            process_queue();
            }, 5*1000);
        }
    }  

    public static void process_queue() {
        //processes queue
        System.out.println("boom");

    }
}

任何帮助将不胜感激。

【问题讨论】:

  • 你遇到了什么问题?
  • 我需要能够不断地监听传入的消息,但每 5 秒处理一次来自 db 的队列。我在 while 循环中运行计时器时遇到问题。
  • 安排一次任务,重复。您调用schedule 的线程无关紧要,Timer 为计划任务维护自己的线程。
  • 如果别无选择,我想我可以在完成后安排一次任务。

标签: java multithreading timer counter


【解决方案1】:

所以你的代码的问题在这里:

//listens for incoming messages
while(true) {

    //process queue
    timer.schedule(new TimerTask() {
    process_queue();
    }, 5*1000);
}

是它会安排无限的任务 - 这是一个无限循环,它会产生所有将在 5 秒后运行的任务。

试试这样的:

public void run() {

        //listens for incoming messages
        while(true) {
            process_queue();
            sleep(5000); //watch out for Exception handling (i.e. InterruptedException)
        }
    }

尽管在当今的软件开发趋势中,您希望避免 blocking 等待(即 sleep() 方法阻塞当前线程)。见 Akka 演员 - http://akka.io/

您还说您希望每 5 秒运行一次方法,但 need to be able to constantly listen for incoming messages。你能澄清一下吗?干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多