guava Futures

本文通过示例代码展示了如何使用Guava库中的线程工具进行任务调度,包括使用ListenableFuture、Futures.transform、Futures.allAsList及Futures.addCallback等API来管理和协调异步任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class GuavaThreadTransform {
    private static final int THREAD_NUM = 10;
    private volatile boolean threadIsSuc = false;
    private int[] lock = new int[0];
    ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(THREAD_NUM));
    @Test
    public void test() throws ExecutionException, InterruptedException {
        ListenableFuture<Integer> future1 = listeningExecutorService.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                try {
                    System.out.println(Thread.currentThread().getName() + "-start");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 10;
            }
        });

        //Futures.transform转换结果
        ListenableFuture<Person> transformedFuture = Futures.transform(future1, new Function<Integer, Person>() {
            public Person apply(Integer list) {
                System.out.println("start to transform sync..");
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("finish transform sync!");

                return new Person("hi");
            }
        });

        System.out.println("transform sync finished?" + transformedFuture.get().getName());

        ListenableFuture<Integer> future2 = listeningExecutorService.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName() + "-start");
                try {
                    Thread.sleep(1000);
//                    throw new Exception("future2 error");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 20;
            }
        });

        //Futures.allAsList:对多个ListenableFuture的合并,  // 返回一个当所有Future成功时返回多个Future返回值组成的List对象。  // 注:当其中一个Future失败或者取消的时候,将会进入失败或者取消。
        ListenableFuture allAsListFuture = Futures.allAsList(transformedFuture, future2);

        //Futures.addCallback:在线程结束时,立即调用FutureCallBack()
        Futures.addCallback(allAsListFuture, new FutureCallback<List>() {
            public void onSuccess(List list) {
                synchronized (lock) {
                    threadIsSuc = true;
                    System.out.println("future success! size:" + list.size());
                    for (Object o : list) {
                        System.out.println("Object class:" + o.getClass());
                        if (o instanceof Person) {
                            System.out.println("Person name:" + ((Person) o).getName());
                        }
                    }
                }
            }

            public void onFailure(Throwable throwable) {
                System.out.println("why onFailure?" + throwable.getMessage());
                System.out.println("why onFailure?" + throwable.getCause());
            }
        });


        ListenableFuture<Integer> future3 = listeningExecutorService.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName() + "-start");
                try {
                    Thread.sleep(1000);
                    throw new Exception("future3 error");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 20;
            }
        });

        // successfulAsList:和allAsList相似,唯一差别是对于失败或取消的Future返回值用null代替。不会进入失败或者取消流程。
        List futureList = (List) Futures.successfulAsList(allAsListFuture, future3).get();
        for (Object o : futureList) {
            System.out.println("o:" + o);
        }

    }

转载于:https://my.oschina.net/legend1989/blog/782567

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值