欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-02 11:25:52
详解jdk中executorservice与callable和future对线程的支持 1、代码背景:     假如有thread1、...

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

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