当前位置:嗨网首页>书籍在线阅读

17-案例实现

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

案例实现

根据如下步骤来实现本案例。

1.创建一个名为 Result 的类,用来存储本例中执行并发任务后的返回结果:

public class Result {

2.声明两个私有变量,一个名为 nameString 型变量和一个名为 valueint 型变量:

private String name;
private int value;

3.实现 get()set() 方法,以设置和返回 namevalue 的值:

public String getName() {
  return name;
}
public void setName(String name) {
  this.name = name;
}
public int getValue() {
  return value;
}
public void setValue(int value) {
  this.value = value;
}

4.创建一个名为 Task 的类,并实现泛型为 ResultCallable 接口:

public class Task implements Callable<Result> {

5.声明一个名为 name 的私有 String 型变量:

private final String name;

6.实现该类的构造方法并初始化类中变量:

public Task(String name) {
  this.name=name;
}

7.实现类中的 call() 方法。在本案例中,该方法会返回一个 Result 实例对象:

@Override
public Result call() throws Exception {

8.在控制台打印任务启动的相关信息:

System.out.printf("%s: Staring\n",this.name);

9.等待一段随机时间:

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();
}

10.计算5个随机数字之和,生成一个 int 型数值,并在 Result 实例对象中返回它:

int value=0;
for (int i=0; i<5; i++){
  value+=(int)(Math.random()*100);
}

11.创建一个 Result 实例对象,并使用 Task 对象的名称和之前操作获取的结果来初始化对象中的变量:

Result result=new Result();
result.setName(this.name);
result.setValue(value);

12.在控制台打印任务结束的相关信息:

System.out.println(this.name+": Ends");

13.返回一个 Result 对象:

  return result;
}

14.至此,开始实现应用程序的入口,创建包含 main()方 法的 Main 类:

public class Main {
  public static void main(String[] args) {

15.用 Executors 类中的 newCachedThreadPool() 方法来创建一个 ThreadPool Executor 对象:

ExecutorService executor=(ExecutorService)Executors
                                       .newCachedThreadPool();

16.创建一个 Task 对象列表,创建10个 Task 实例对象并加入列表中:

List<Task> taskList=new ArrayList<>();
for (int i=0; i<10; i++){
  Task task=new Task("Task-"+i);
  taskList.add(task);
}

17.创建一个 Future 对象列表。 Future 对象的泛型为 Result 类:

List<Future<Result>>resultList=null;

18.调用 ThreadPoolExecutor 类中的 invokeAll() 方法,返回结果会传给之前创建的 Future 对象列表:

try {
  resultList=executor.invokeAll(taskList);
} catch (InterruptedException e) {
  e.printStackTrace();
}

19.调用 shutdown() 方法来终止执行器:

executor.shutdown();

20.打印 Future 对象列表中存储的执行结果:

System.out.println("Main: Printing the results");
for (int i=0; i<resultList.size(); i++){
  Future<Result> future=resultList.get(i);
  try {
    Result result=future.get();
    System.out.println(result.getName()+": "+result.getValue());
  } catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
  }
}