前两种线程执行的干活线程的方法无返回值,现在方法出现一个返回值。
一、哪么线程如何执行这个方法?
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(); } } } |