Java多线程编程(二)

时间:2024-01-13 20:54:50

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

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

【程序实例】

 public class TaskWithResult implements Callable<String> {

     private int id;

     public TaskWithResult(int id) {
this.id = id;
} @Override
public String call() throws Exception {
return "result of TaskWithResult " + id + " : sum() = " + Sum(id);
} private int Sum(int id) {
return (id * (id + 1)) / 2;
} }
 public class Main {

     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();
}
} }

【运行结果】

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