File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed
toolTest/common/src/test/java/tool/guava Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change 11package tool .guava ;
22
3+ import com .google .common .util .concurrent .ListeningExecutorService ;
34import com .google .common .util .concurrent .RateLimiter ;
45import org .junit .jupiter .api .Test ;
56
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments