Skip to content

Commit f8460dc

Browse files
多任务
1 parent d31571a commit f8460dc

File tree

3 files changed

+67
-24
lines changed

3 files changed

+67
-24
lines changed

src/main/java/com/java8/completefuture/CompleteFutureDemo.java

+2-6
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,8 @@ public static void supplyAsyncGet() {
2424
try {
2525
//获取返回值,2秒超时
2626
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);
27+
} catch (Exception e) {
28+
logger.error("completableFuture.get error.", e);
3329
}
3430
logger.info("result:"+result);
3531
}

src/main/java/com/java8/completefuture/OfAllGetDemo.java

+19-18
Original file line numberDiff line numberDiff line change
@@ -23,28 +23,27 @@ public static void main(String[] args) {
2323
public static void allOfGet() {
2424
//该线程池仅用于示例,实际建议使用自定义的线程池
2525
ExecutorService executorService = Executors.newCachedThreadPool();
26-
String word1 = "word1";
27-
String word2 = "word2";
2826

2927
//线程安全的list,适合写多读少的场景
30-
List<String> strList = Collections.synchronizedList(new ArrayList<>(50));
28+
List<String> resultList = Collections.synchronizedList(new ArrayList<>(50));
3129
CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(
32-
() -> getResult(word1, 1000), executorService)
30+
() -> runTask("result1", 1000), executorService)
3331
.whenComplete((result, throwable) -> {
34-
//任务完成时执行
32+
//任务完成时执行。用list存放任务的返回值
3533
if (result != null) {
36-
strList.add(result);
34+
resultList.add(result);
3735
}
36+
//触发异常
3837
if (throwable != null) {
3938
logger.error("completableFuture1 error:{}", throwable);
4039
}
4140
});
4241

4342
CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(
44-
() -> getResult(word2, 1500), executorService)
43+
() -> runTask("result2", 1500), executorService)
4544
.whenComplete((result, throwable) ->{
4645
if (result != null) {
47-
strList.add(result);
46+
resultList.add(result);
4847
}
4948
if (throwable != null) {
5049
logger.error("completableFuture2 error:{}", throwable);
@@ -57,27 +56,29 @@ public static void allOfGet() {
5756
futureList.add(completableFuture2);
5857

5958
try {
60-
//多个任务,耗时不超时2秒
61-
CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0]))
62-
.get(2, TimeUnit.SECONDS);
63-
} catch (InterruptedException | ExecutionException e) {
64-
logger.error("CompletableFuture.allOf InterruptedException error.", e);
65-
} catch (TimeoutException e) {
66-
logger.error("CompletableFuture.allOf TimeoutException error.", e);
59+
//多个任务
60+
CompletableFuture[] futureArray = futureList.toArray(new CompletableFuture[0]);
61+
//将多个任务,汇总成一个任务,总共耗时不超时2秒
62+
CompletableFuture.allOf(futureArray).get(2, TimeUnit.SECONDS);
63+
} catch (Exception e) {
64+
logger.error("CompletableFuture.allOf Exception error.", e);
6765
}
68-
List<String> resultList = new ArrayList<>(strList);
66+
List<String> list = new ArrayList<>(resultList);
6967

70-
resultList.forEach(System.out::println);
68+
list.forEach(System.out::println);
7169
}
7270

7371

74-
private static String getResult(String result, int millis) {
72+
private static String runTask(String result, int millis) {
7573
try {
74+
//此处忽略实际的逻辑,用sleep代替
7675
//任务耗时。可以分别设置1000和3000,看未超时和超时的不同结果。
7776
Thread.sleep(millis);
7877
} catch (InterruptedException e) {
7978
logger.error("supplyAsyncGet error.");
8079
}
8180
return result;
8281
}
82+
83+
8384
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.thread.threadpool;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
import java.util.concurrent.*;
8+
9+
@Slf4j
10+
public class SubmitDemo {
11+
public static void main(String[] args) {
12+
submit();
13+
}
14+
15+
public static void submit() {
16+
long start = System.currentTimeMillis();
17+
//该线程池仅用于示例,实际建议使用自定义的线程池
18+
ExecutorService executor = Executors.newCachedThreadPool();
19+
Future<String> future1 = executor.submit(() -> {
20+
Thread.sleep(4000);
21+
return "task1";
22+
});
23+
Future<String> future2 = executor.submit(() -> {
24+
Thread.sleep(5000);
25+
return "task2";
26+
});
27+
28+
List<String> resultList = new ArrayList<>();
29+
addFutureResult(future1, resultList, 2,"add result1 error.");
30+
31+
addFutureResult(future2, resultList, 2, "add result2 error.");
32+
33+
System.out.println("it cost time :"+ (System.currentTimeMillis()-start) );
34+
resultList.forEach(System.out::println);
35+
}
36+
37+
private static void addFutureResult(Future<String> future, List<String> resultList, int timeout, String s) {
38+
try {
39+
String result = future.get(timeout, TimeUnit.SECONDS);
40+
resultList.add(result);
41+
} catch (Exception e) {
42+
log.error(s, e);
43+
}
44+
}
45+
46+
}

0 commit comments

Comments
 (0)