首页 > 开发 > Java > 正文

详解JDK中ExecutorService与Callable和Future对线程的支持

2024-07-13 10:11:20
字体:
来源:转载
供稿:网友

详解JDK中ExecutorService与Callable和Future对线程的支持

1、代码背景:

    假如有Thread1、Thread2、Thread3、Thread4四条线程分别统计C、D、E、F四个盘的大小,所有线程都统计完毕交给Thread5线程去做汇总,应当如何实现?

2、代码:

    统计“盘子”大小的代码,此处实现jdk中的Callable接口,

package com.wang.test.concurrent;  import java.util.concurrent.Callable;  public class Task1 implements Callable<Integer> {    private int x;   private int y;      public Task1(int x, int y) {     this.x = x;     this.y = y;   }    @Override   public Integer call() throws Exception {     return x*y;   }  } 

    统计汇总的代码,也是实现jdk中的Callable接口,

package com.wang.test.concurrent;  import java.util.concurrent.Callable;  public class Task2 implements Callable<Integer> {    private int x;   private int y;   private int q;   private int w;      public Task2(int x, int y, int q, int w) {     this.x = x;     this.y = y;     this.q = q;     this.w = w;   }    @Override   public Integer call() throws Exception {     return x + y + q + w;   }  } 

     客户端:使用JDK中Executors.newFixedThreadPool方法创建ExecutorService,ExecutorService的submit方法接收Callable接口的实现,JDK内部将弄成线程处理,使用Future接收submit方法的返回值,当future调用get方法时,如果线程还没有执行完,程序阻塞在这里,知道线程执行完。

package com.wang.test.concurrent;  import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;  public class Client {    public static void main(String[] args) throws Exception {     ExecutorService pool = Executors.newFixedThreadPool(4);      Task1 t1 = new Task1(1,2);     Task1 t2 = new Task1(23,34);     Task1 t3 = new Task1(23,456);     Task1 t4 = new Task1(3,33);     Future<Integer> f1 = pool.submit(t1);     Future<Integer> f2 = pool.submit(t2);     Future<Integer> f3 = pool.submit(t3);     Future<Integer> f4 = pool.submit(t4);          //Future调用get方法时,如果线程还没有执行完,程序阻塞在这里     Task2 t5 = new Task2(f1.get(), f2.get(), f3.get(), f4.get());     Future<Integer> f5 = pool.submit(t5);          System.out.println(f5.get());          pool.shutdown();   } } 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表