Skip to content

Commit 7472e6b

Browse files
committed
💚 🧱 🚚
1 parent 45f6298 commit 7472e6b

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

toolTest/common/src/test/java/tool/guava/GuavaTest.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package tool.guava;
22

3+
import com.google.common.util.concurrent.ListeningExecutorService;
34
import com.google.common.util.concurrent.RateLimiter;
45
import org.junit.jupiter.api.Test;
56

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package tool.guava;
2+
3+
import com.google.common.util.concurrent.*;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.util.concurrent.ExecutorService;
7+
import java.util.concurrent.Executors;
8+
import java.util.concurrent.TimeUnit;
9+
10+
11+
/**
12+
*
13+
* ListeningExecutorService 是Guava对Java标准库ExecutorService的扩展,
14+
* 1、支持回调机制:不再需要手动get()等待结果,任务完成后自动触发回调
15+
* 2、返回ListenableFuture:支持链式操作
16+
* 3、更灵活的异步组合:轻松合并多个异步任务,处理超时、异常等场景。
17+
*
18+
* @date 2022/9/26
19+
*/
20+
21+
public class ListeningExecutorServiceTest {
22+
23+
24+
25+
26+
@Test void t1(){
27+
28+
ExecutorService executorService = Executors.newFixedThreadPool(8);
29+
30+
ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);
31+
32+
33+
ListenableFuture<?> future = listeningExecutorService.submit(() -> {
34+
try {
35+
Thread.sleep(1000L);
36+
} catch (InterruptedException e) {
37+
38+
}
39+
System.out.println("hello world");
40+
});
41+
42+
Futures.addCallback(future, new FutureCallback<Object>() {
43+
@Override
44+
public void onSuccess(Object result) {
45+
System.out.println("Task success");
46+
}
47+
@Override
48+
public void onFailure(Throwable t) {
49+
System.out.println("Task fail");
50+
}
51+
}, MoreExecutors.directExecutor());
52+
53+
54+
try {
55+
TimeUnit.SECONDS.sleep(5);
56+
} catch (InterruptedException e) {
57+
throw new RuntimeException(e);
58+
}
59+
}
60+
61+
62+
63+
64+
65+
}

0 commit comments

Comments
 (0)