- 对所有 Java 源文件应用统一的代码格式化 - 统一缩进为 4 个空格 - 清理尾随空白字符和文件末尾换行 - 优化导入语句组织 - 总计格式化 654 个 Java 文件 有问题可以回滚或者找我聊
58 lines
1.9 KiB
Java
58 lines
1.9 KiB
Java
package com.starry.common.utils;
|
|
|
|
import java.util.concurrent.*;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
/**
|
|
* @author admin 线程相关工具类
|
|
* @since 2022/7/25
|
|
*/
|
|
public class ThreadsUtils {
|
|
private static final Logger logger = LoggerFactory.getLogger(ThreadsUtils.class);
|
|
|
|
/**
|
|
* 停止线程池 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务. 如果超时, 则调用shutdownNow,
|
|
* 取消在workQueue中Pending的任务,并中断所有阻塞函数. 如果仍然超時,則強制退出. 另对在shutdown时线程本身被调用中断做了处理.
|
|
*/
|
|
public static void shutdownAndAwaitTermination(ExecutorService pool) {
|
|
if (pool != null && !pool.isShutdown()) {
|
|
pool.shutdown();
|
|
try {
|
|
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
|
|
pool.shutdownNow();
|
|
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
|
|
logger.info("Pool did not terminate");
|
|
}
|
|
}
|
|
} catch (InterruptedException ie) {
|
|
pool.shutdownNow();
|
|
Thread.currentThread().interrupt();
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 打印线程异常信息
|
|
*/
|
|
public static void printException(Runnable r, Throwable t) {
|
|
if (t == null && r instanceof Future<?>) {
|
|
try {
|
|
Future<?> future = (Future<?>) r;
|
|
if (future.isDone()) {
|
|
future.get();
|
|
}
|
|
} catch (CancellationException ce) {
|
|
t = ce;
|
|
} catch (ExecutionException ee) {
|
|
t = ee.getCause();
|
|
} catch (InterruptedException ie) {
|
|
Thread.currentThread().interrupt();
|
|
}
|
|
}
|
|
if (t != null) {
|
|
logger.error(t.getMessage(), t);
|
|
}
|
|
}
|
|
}
|