为什么我的一些计时器根本不执行任务?
我正在开发一个多计时器任务项目。
首先,我设计了一些扩展TimerTask的类并重写run()方法。在 run() 方法中,将打印一行当前时间。
其次,一个Timer是这样初始化的。
......
DataTask task1 = new DataTask();
myTaskList.add(task1);
DataTask task2 = new DataTask();
myTaskList.add(task2);
DataTask task3 = new DataTask();
myTaskList.add(task3);
DataTask task4 = new DataTask();
myTaskList.add(task4);
for(TimerTask task : myTaskList)
{
Timer timer = new Timer();
timer.schedule(task,1,60*1000);
}
......
public class DataTask extends TimerTask
{
@override
public void run()
{
System.out.println("print sth");
}
}
一个线程中的一项任务。是这样吗?
有时任务会工作,但有时任务不会打印任何内容,而线程仍处于活动状态,没有任何异常。
这可能是什么原因?
I'm developing a multi-timertask project.
First of all, I design some classes extended TimerTask and override the run() method. In the run() method, a line will be printed with current time.
Secondly, a Timer is initialized like this.
......
DataTask task1 = new DataTask();
myTaskList.add(task1);
DataTask task2 = new DataTask();
myTaskList.add(task2);
DataTask task3 = new DataTask();
myTaskList.add(task3);
DataTask task4 = new DataTask();
myTaskList.add(task4);
for(TimerTask task : myTaskList)
{
Timer timer = new Timer();
timer.schedule(task,1,60*1000);
}
......
public class DataTask extends TimerTask
{
@override
public void run()
{
System.out.println("print sth");
}
}
One task in one thread. Is that Right?
Sometimes the tasks work, however, sometimes the tasks will not print anything, without any Exception, while the thread is still alive.
What could be the reason for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,在底层,计时器利用单个线程来调度提交的任务,但在您的情况下,由于您使用多个计时器,是的,每个任务都将在单独的线程中执行。如果您需要利用多个线程来运行多个任务,请查看并发包中的执行器。查看 ExecutorService 类的 Javadoc例如。
No, under the hood, the
Timer
utilizes a single thread for scheduling the submitted tasks but in your case since you are using multiple timers, yes, every task would execute in a separate thread. If you have the requirement to run multiple tasks by utilizing multiple threads, look into Executors in the concurrent package. Look into the Javadoc of ExecutorService class for examples.