从Java线程中运行计时器
我会每5秒钟从我的线程中链接执行一个方法。我的课程大纲如下从Java线程中运行计时器,java,multithreading,timer,counter,Java,Multithreading,Timer,Counter,我会每5秒钟从我的线程中链接执行一个方法。我的课程大纲如下 private static Timer timer = new Timer(); public class myThread implements Runnable { public void run() { //listens for incoming messages while(true) { //process queue time
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");
}
}
任何帮助都将不胜感激。因此,您的代码存在以下问题:
//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)
}
}
尽管在当今的软件开发趋势中,您希望避免阻塞
等待(即sleep()方法阻塞当前线程)。见阿克卡演员-
您还表示希望每5秒运行一次方法,但
需要能够不断侦听传入消息。你能澄清一下吗?干杯您面临什么问题?我需要能够不断地侦听传入的消息,但每5秒处理来自db的队列。我在while循环中运行计时器时遇到问题。请将任务安排一次,并重复执行。你调用的schedule
线程是不相关的,Timer
为计划任务维护自己的线程。我想如果没有其他选择,我可以在任务完成后安排一次任务。