工具类
package com.changan.incalleventservice.utils;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ExecutorUtil {
/**
* 默认缓冲队列长度:500
*/
private static final int DEFAULT_POOL_CAPACITY = 500;
/**
* 业务线程池定义
* 核心线程数:可以根据Runtime.getRuntime().availableProcessors()
*/
private static final ThreadPoolExecutor taskExecutor = new ThreadPoolExecutor(
4,
16,
10,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(DEFAULT_POOL_CAPACITY),
Executors.defaultThreadFactory(), (r, executor) -> LogUtil.e(r.toString() + "执行了拒绝策略"));
/**
* 清缓存线程池
*/
public static void CLEARESERVICE() {
if (taskExecutor.getQueue().size() > 0) {
taskExecutor.getQueue().clear();
LogUtil.w("getPoolExecutorInfo ,clear,clear,clear");
}
}
/**
* 把父线程的MDC内容赋值给子线程
*
* @param runnable
*/
public static void execute(Runnable runnable) {
taskExecutor.execute(() -> run(runnable));
}
public static <T> Future<T> submit(Callable<T> task) {
return taskExecutor.submit(() -> call(task));
}
/**
* 子线程委托的执行方法
*
* @param runnable {@link Runnable}
*/
private static void run(Runnable runnable) {
runnable.run();// 执行异步操作
}
/**
* 子线程委托的执行方法
*
* @param task {@link Callable}
*/
private static <T> T call(Callable<T> task) throws Exception {
return task.call(); // 执行异步操作
}
}
使用:
ExecutorUtil.execute(() -> {
while (true) {
try {
LogUtil.d("serverSocket=" + serverSocket + ",inetSocketAddress=" + inetSocketAddress+"开始等待客户端接入");
Socket socket = serverSocket.accept();
if (!TCPSocketManager.getInstance().phoneStatus) {
LogUtil.d("开始读取");
loopRead(socket, inetSocketAddress); // 循环读取
}else {
canNotConected(socket);
}
LogUtil.d("结束读取 等待新客户端接入中 :: phostate"+TCPSocketManager.getInstance().phoneStatus);
} catch (Throwable e) {
LogUtil.d("Socket通信有问题 原因:"+e.getMessage());
e.printStackTrace();
close();
}
}
});