Skip to content

Commit 99522ae

Browse files
CompletableFuture
1 parent 0e88e6b commit 99522ae

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.java8.completefuture;
2+
3+
import org.apache.log4j.LogManager;
4+
import org.apache.log4j.Logger;
5+
6+
import java.util.concurrent.*;
7+
8+
9+
public class CompleteFutureDemo {
10+
11+
private static Logger logger= LogManager.getLogger(CompleteFutureDemo.class);
12+
13+
public static void main(String[] args) {
14+
supplyAsyncGet();
15+
}
16+
17+
public static void supplyAsyncGet() {
18+
//该线程池仅用于示例,实际建议使用自定义的线程池
19+
ExecutorService executorService = Executors.newCachedThreadPool();
20+
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(()
21+
-> runTask(), executorService);
22+
23+
String result = null;
24+
try {
25+
//获取返回值,2秒超时
26+
result = completableFuture.get(2, TimeUnit.SECONDS);
27+
} catch (InterruptedException e) {
28+
logger.error("InterruptedException error.", e);
29+
} catch (ExecutionException e) {
30+
logger.error("ExecutionException error.", e);
31+
} catch (TimeoutException e) {
32+
logger.error("TimeoutException error.", e);
33+
}
34+
logger.info("result:"+result);
35+
}
36+
37+
private static String runTask() {
38+
try {
39+
//任务耗时。可以分别设置1000和3000,看未超时和超时的不同结果。
40+
Thread.sleep(1000);
41+
} catch (InterruptedException e) {
42+
logger.error("supplyAsyncGet error.");
43+
}
44+
return "supplyAsyncGet";
45+
}
46+
}

0 commit comments

Comments
 (0)