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?
No, under the hood, the
Timerutilizes 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.