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
作者: Acode
出处: http://www.cnblogs.com/acode/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可留言咨询.