有返回值的多執行緒示例
阿新 • • 發佈:2019-01-29
問題場景
近期遇到用多執行緒優化程式,但是必須帶有返回值,實現Runnable介面不可行,檢視API,可以用Callable介面,試舉一例。
package thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by yangyouxing
* date on 2017/6/1.
*/
public class TestCallable {
private static class Worker implements Callable<String> {
private int i;
public Worker(int i) {
this.i = i;
}
@Override
public String call() throws Exception {
return "*******" + i + "*******";
}
}
public static void main(String[] args) {
try {
List<Future<String>> list = new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 50; i++) {
list.add(executorService.submit(new Worker(i)));
}
executorService.shutdown();
executorService.awaitTermination(1 , TimeUnit.DAYS);
//獲取返回的值
List<String> values = new ArrayList<>();
for (Future<String> aList : list) {
//判斷任務是否完成
if (aList.isDone()) {
values.add(aList.get());
}
}
for (String s : values) {
System.out.println(s);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}