Producing return values from tasks 建立干活线程时带有返回值

前两种线程执行的干活线程的方法无返回值,现在方法出现一个返回值。

一、哪么线程如何执行这个方法?

1》对于一个对象调用方法,有一个返回值

2》现在有多个线程时,对应对象也是多个,因此返回值肯定是用袋子类对象(容器或是数组)来装返回值。

3》根据方法的返回值来选择袋子类对象。

   对于数组肯定不合适,因为是newCachedThreadPool 线程池的线程不确定是多少,所以返回值选择容器对象

  ArrayList 来装返回值

 二、例子

    1、实现Callable<String> 代替Runnable接口

    2、方法call()代替 run()方法

   4、执行任务submit 代替 execute

   3、执行任务只能用Executor了。

   4、线程执行任务的返回值,放在Future对象里面,是submit()产生的,返回值得类型由Callable<String>的类参数确定,这个例子是String。

   5、返回时不停加到容器ArrayList 即可。

You can query the Future with isDone( ) to see if it has
completed,查询看任务是否完成,是否有返回值了。

package concurrency;

import java.util.concurrent.*;
import java.util.*;
class TaskWithResult implements Callable<String> {
private int id;

public TaskWithResult(int id) {
this.id = id;
}
public String call() {
return "result of TaskWithResult " + id;
}
}
public class CallableDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++)
results.add(exec.submit(new TaskWithResult(i)));
for (Future<String> fs : results)
try {

System.out.println(fs.get());
} catch (InterruptedException e) {
System.out.println(e);
return;
} catch (ExecutionException e) {
System.out.println(e);
} finally {
exec.shutdown();
}
}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值