Java多线程编程(二)

在 Java多线程编程(一) 中的多线程并没有返回值,本文将介绍带返回值的多线程。

要想有返回值,则需要实现新的接口Callable而不再是Runnable接口,实现的方法也改为call()方法,执行器也不再是调用execute(),而是submit()

【程序实例】

 1 public class TaskWithResult implements Callable<String> {
 2 
 3     private int id;
 4 
 5     public TaskWithResult(int id) {
 6         this.id = id;
 7     }
 8 
 9     @Override
10     public String call() throws Exception {
11         return "result of TaskWithResult " + id + " : sum() = " + Sum(id);
12     }
13 
14     private int Sum(int id) {
15         return (id * (id + 1)) / 2;
16     }
17 
18 }
 1 public class Main {
 2 
 3     public static void main(String[] args) {
 4         ExecutorService exec = Executors.newCachedThreadPool();
 5         ArrayList<Future<String>> results = new ArrayList<Future<String>>();
 6         for (int i = 0; i < 10; i++)
 7             results.add(exec.submit(new TaskWithResult(i)));
 8         for (Future<String> fs : results)
 9             try {
10                 System.out.println(fs.get());
11             } catch (InterruptedException e) {
12                 System.out.println(e);
13                 return;
14             } catch (ExecutionException e) {
15                 System.out.println(e);
16             } finally {
17                 exec.shutdown();
18             }
19     }
20 
21 }

【运行结果】

 1 result of TaskWithResult 0 : sum() = 0
 2 result of TaskWithResult 1 : sum() = 1
 3 result of TaskWithResult 2 : sum() = 3
 4 result of TaskWithResult 3 : sum() = 6
 5 result of TaskWithResult 4 : sum() = 10
 6 result of TaskWithResult 5 : sum() = 15
 7 result of TaskWithResult 6 : sum() = 21
 8 result of TaskWithResult 7 : sum() = 28
 9 result of TaskWithResult 8 : sum() = 36
10 result of TaskWithResult 9 : sum() = 45

 

posted @ 2016-08-19 11:51  Acode  阅读(237)  评论(0编辑  收藏  举报
您是本站第访问量位访问者!