ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 10,TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000));
1. Use a list to save the future object returned by the callable task of threadpoolexecutor submit:
List<Future<Object>> futureList...threadPool.submit(new Callable(){...})
Traverse the list in the main thread and call the get () method of ure to obtain the return value of the task:
for (Future<Object> future : futureList) { future.get();}
Because submit tasks are not necessarily completed by adding them to the list maintained by themselves, each future object traversed from the list is not necessarily in the completed State. At this time, get () is called () the method will be blocked, so that the threads that are behind the list but completed first will increase the additional waiting time.
Therefore, if you use list to save the future object, it is not necessarily taken out first.
2. Package threadpoolexecutor through completionservice, and then call its take () method to get the future object.
CompletionService<Object> completionService = new ExecutorCompletionService<Object>(threadPoolExecutor);completionService.submit(new Callable(){...});for(;;){ Future<Object> future=completionService.take();}
Completionservice maintains a blockingqueue that stores the future object. The future object will be added to this queue only when the State of the future object ends. The take () method will retrieve the future object from the queue. If the queue is empty, it will be blocked until a completed future object is added to the queue.
Therefore, when using completionservice, the first completed task must be taken out first, which reduces the unnecessary waiting time.