使用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);
}
}
然后就可以开始愉快的使用啦~