4.4运行并发任务并返回所有运行结果
ThreadPoolExecutor提供了一个方法,它允许你发送给executor一列的任务链表,并且等待这些任务的终结。请看下面实例。
Result类的定义如下所示:
/**
* This class stores the resultgenerated by one task
*
*/
public class Result {
/**
* The name of the task that generates theresult
*/
private String name;
/**
* The value of the task that generates theresult
*/
private intvalue;
/**
* Returns the name of the task
* @return Name of the task that generates the result
*/
public String getName() {
return name;
}
/**
* Establish the name of the task
* @param name The name of the task that generates the result
*/
public voidsetName(String name) {
this.name = name;
}
/**
* Returns the value of the result
* @return The value of the result
*/
public intgetValue() {
return value;
}
/**
* Establish the value of the result
* @param value The value of the result
*/
public voidsetValue(intvalue) {
this.value = value;
}
}
定义Task类,实现必要的逻辑。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
importjava.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* This class implements the task ofthis example. It waits during a random
* period of time and then calculatethe sum of five random numbers
*
*/
public class Task implements Callable<Result> {
/**
* The name of the Task
*/
private String name;
/**
* Constructor of the class
* @param name Initializes the name of the task
*/
public Task(String name) {
this.name=name;
}
/**
* Main method of the task. Waits during arandom period of time and then
* calculates the sum of five random numbers
*/
@Override
public Result call() throws Exception {
// Writes a message to the console
System.out.printf("%s: Staring\n",this.name);
// Waits during a random period of time
try {
Long duration=(long)(Math.random()*10);
System.out.printf("%s: Waiting %d seconds for results.\n",this.name,duration);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Calculates the sum of five random numbers
int value=0;
for (int i=0; i<5; i++){
value+=(int)(Math.random()*100);
}
// Creates the object with the results
Result result=new Result();
result.setName(this.name);
result.setValue(value);
System.out.printf("%s: Ends\n",this.name);
// Returns the result object
return result;
}
public staticvoidmain(String []args){
// Create an executor
ExecutorServiceexecutor=(ExecutorService)Executors.newCachedThreadPool();
// Create three tasks and stores them in a List
List<Task> taskList=newArrayList<Task>();
for (int i=0; i<3; i++){
Task task=new Task("Task-"+i);
taskList.add(task);
}
// Call the invokeAll() method
List<Future<Result>>resultList=null;
try {
resultList=executor.invokeAll(taskList);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Finish the executor
executor.shutdown();
// Writes the results to the console
System.out.printf("Core: Printing the results\n");
for (int i=0; i<resultList.size(); i++){
Future<Result>future=resultList.get(i);
try {
Result result=future.get();
System.out.printf("%s: %s\n",result.getName(),result.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
运行结果:
Task-0:Staring
Task-2:Staring
Task-1:Staring
Task-2:Waiting 3 seconds for results.
Task-0:Waiting 0 seconds for results.
Task-1:Waiting 4 seconds for results.
Task-0:Ends
Task-2:Ends
Task-1:Ends
Core:Printing the results
Task-0:175
Task-1:206
Task-2: 101