Java使用guava快速构建一个线程工具类

使用guava快速构建一个线程工具类

主要目的是省去了线程池创创建等一些繁琐操作,可以快速开始业务代码。

1.添加pom依赖


     <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.0</version>
        </dependency>

2.添加工具类


import com.google.common.util.concurrent.*;

import javax.annotation.Nullable;
import java.util.UUID;
import java.util.concurrent.*;

public class MyThreadUtil {

    /**
     * 用户自定义线程池
     */
    private static ExecutorService executor = new ThreadPoolExecutor(10, 10,
            60L, TimeUnit.SECONDS,
            new ArrayBlockingQueue(10));

    /**
     * guava定义线程池
     */
    private static ListeningExecutorService pool = MoreExecutors.listeningDecorator(
            new ThreadPoolExecutor(5, 200,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(1024),
                    new ThreadFactoryBuilder()
                            .setNameFormat("task-pool-%d").build(),
                    new ThreadPoolExecutor.AbortPolicy())
    );

    private static ConcurrentHashMap<String, String> results = new ConcurrentHashMap<>();


    public static String run(Callable call){
        ListenableFuture future = pool.submit(call);

        String id = UUID.randomUUID().toString();

        FutureCallback<String> callback = new FutureCallback<String>() {
            @Override
            public void onSuccess(@Nullable String s) {
                System.out.println("获取响应值" + s);
                results.put(id, s);
            }

            @Override
            public void onFailure(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        };
        Futures.addCallback(future, callback, pool);
        return id;
    }

    public static String getResult(String id){
        return results.get(id);
    }


}

然后就可以开始愉快的使用啦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值