背景:
java 并发中concurrent包下有很多关于并发的操作,使用最常见的为ExecutorService
支持类型:
Callable
Runnable
此两种类型中的Callable是有返回值的,那么如果很好的获取执行结果?
依赖:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>
实现:
public static void getResult() throws Exception {
long begin = System.currentTimeMillis();
ExecutorService service = Executors.newFixedThreadPool(10000);
List<StringCallable> all = new ArrayList<StringCallable>();
for (int i = 0; i < 1000; i++) {
all.add(new StringCallable(i));
}
List<Future<String>> result = service.invokeAll(all);
for (Future<String> future : result) {
String list = future.get();
System.out.println(list);
}
service.shutdown();
long end = System.currentTimeMillis();
System.out.println("--" + (end - begin));
}
直接获取:
public static void get() throws Exception {
long begin = System.currentTimeMillis();
ExecutorService service = Executors.newFixedThreadPool(10000);
for (int i = 0; i < 1000; i++) {
Future<String> resul = service.submit(new StringCallable(1000));
System.out.println(resul.get());
}
service.shutdown();
long end = System.currentTimeMillis();
System.out.println("cost:" + (end - begin));
}
后者会有等待而不是并发,因此在使用的时候需要注意
基类:
class StringCallable implements Callable<String> {
private int index = 0;
public StringCallable(int index) {
super();
this.index = index;
}
public String call() throws Exception {
System.out.println("index:" + index);
return RandomStringUtils.random(12, "abcdefghijklmnopqrstuvwxyz");
}
}