I have many unrelated tasks to execute and I have to get the result of the task so I use the FutureTask
.
I submit all the task to the thread pool and use a map to keep track of the task and the FutureTask
to get the result. And two for loops are used:
ExecutorService es = Executors.newCachedThreadPool();
Map<Task, FutureTask<Boolean>> taskResultMap = new HashMap<Task, FutureTask<Boolean>>();
for (int i = 0 ; i < callerList.size(); i++)
{
Caller caller = callerList.get(i);
FutureTask<Boolean> futureTask = new FutureTask<Boolean>(caller);
es.submit(futureTask);
taskResultMap.put(caller, futureTask);
}
for (int i = 0 ; i < callerList.size(); i++)
{
Caller caller = callerList.get(i);
FutureTask<Boolean> task = taskResultMap.get(caller);
System.out.println(caller.getName() + " result is " + task.get());
}
Is this a good practice about ExecutorService and FutureTask? I'm new in multi-thread programming.
Another two questions:
- How can I get the execution time for each thread? print in caller iteself or outside caller?
- When I invoke the
FutureTask.get()
method in for loop, I think theget()
method may be blocked, If a time-consuming task is running, I can't get the result of the next task but to wait. How could I do this?