转载:https://blog.youkuaiyun.com/weixin_38399962/article/details/81979295
工具类
/**
* Description:符合阿里巴巴规范的线程池
* User: zhouzhou
* Date: 2019-01-15
* Time: 14:19
*/
public class ThreadPoolUtil {
public static ThreadPoolExecutor threadPool;
/**
* 无返回值直接执行
* @param runnable
*/
public static void execute(Runnable runnable){
getThreadPool().execute(runnable);
}
/**
* 返回值直接执行
* @param callable
*/
public static <T> Future<T> submit(Callable<T> callable){
return getThreadPool().submit(callable);
}
/**
* 关闭线程池
*/
public static void shutdown() {
getThreadPool().shutdown();
}
/**
* dcs获取线程池
* @return 线程池对象
*/
public static ThreadPoolExecutor getThreadPool() {
if (threadPool != null) {
return threadPool;
} else {
synchronized (ThreadPoolUtil.class) {
if (threadPool == null) {
threadPool = new ThreadPoolExecutor(8, 16, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(32), new ThreadPoolExecutor.CallerRunsPolicy());
}
return threadPool;
}
}
}
}
使用
- 编写Callable类
class TestCallable implements Callable<String> {
private String message;
public TestCallable(String message) {
this.message = message;
}
@Override
public String call() throws Exception {
Thread.sleep(300);
System.out.println(String.format("打印消息%s", message));
return "OK";
}
}
- 编写测试方法
@Test
public void test() throws Exception{
long start = System.currentTimeMillis();
List<Future> futureList = new ArrayList();
// 发送10次消息
for (int i = 0; i < 10; i++) {
try {
Future<String> messageFuture = ThreadPoolUtils.submit(new TestCallable(String.format("这是第{%s}条消息", i)));
futureList.add(messageFuture);
} catch (Exception e) {
e.printStackTrace();
}
}
for (Future<String> message : futureList) {
String messageData = message.get();
}
System.out.println(String.format("共计耗时{%s}毫秒", System.currentTimeMillis() - start));
}
打印结果:
打印消息这是第{2}条消息
打印消息这是第{0}条消息
打印消息这是第{4}条消息
打印消息这是第{1}条消息
打印消息这是第{3}条消息
打印消息这是第{8}条消息
打印消息这是第{5}条消息
打印消息这是第{9}条消息
打印消息这是第{6}条消息
打印消息这是第{7}条消息
共计耗时{661}毫秒
- 当然如果你不想编写Callable类,直接使用匿名内部类(建议)
/**
* Description:
* User: zhouzhou
* Date: 2018-08-23
* Time: 13:28
*/
public class ThreadDemoTest {
@Test
public void test() throws Exception{
long start = System.currentTimeMillis();
List<Future> futureList = new ArrayList();
// 发送10次消息
for (int i = 0; i < 10; i++) {
try {
String msg = String.format("这是第{%s}条消息", i);
Future<String> messageFuture = ThreadPoolUtils.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(300);
System.out.println(String.format("打印消息%s", msg));
return "OK";
}
});
futureList.add(messageFuture);
} catch (Exception e) {
e.printStackTrace();
}
}
for (Future<String> message : futureList) {
String messageData = message.get();
}
System.out.println(String.format("共计耗时{%s}毫秒", System.currentTimeMillis() - start));
}
}