码上敲享录 > java高并发常见问题 > CompletionService的简单用法

CompletionService的简单用法

上一章章节目录下一章 2019-05-29已有1486人阅读 评论(0)

CompletionService的简单用法


解决方法:


1.测试方法,与线程池结合使用


public static void main(String[] args) throws Exception {

CallableDemo callable = new CallableDemo(1,100000);

CallableDemo callable2 = new CallableDemo(1,100);

ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 5, 5L,TimeUnit.SECONDS, new LinkedBlockingDeque());

CompletionService csRef = new ExecutorCompletionService(executor);

csRef.submit(callable);

csRef.submit(callable2);

//CompletionService 的take()方法获取最先执行完的线程的Future对象。

System.out.println(csRef.take().get());

System.out.println(csRef.take().get());

}


2.线程类,实现Callable解决取返回值

import java.util.concurrent.Callable;

public class CallableDemo implements Callable<String> {

private int begin;

private int end;

private int sum;

public CallableDemo(int begin, int end) {

super();

this.begin = begin;

this.end = end;

}


public String call() throws Exception {

for(int i=begin;i<=end;i++){

for(int j=begin;j<=end;j++){

sum+=j;

}

}

Thread.sleep(8000);

return begin+"-" +end+"的和:"+ sum;

}

}


向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
3

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交