74 lines
2.1 KiB
Java
Raw Normal View History

2020-02-13 10:48:51 +08:00
package com.ruoyi.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
2021-10-22 10:04:15 +08:00
import java.util.concurrent.*;
2020-02-13 10:48:51 +08:00
/**
* 线程相关工具类.
2021-10-22 10:04:15 +08:00
*
2020-02-13 10:48:51 +08:00
* @author ruoyi
*/
2021-10-22 10:04:15 +08:00
public class Threads {
2020-02-13 10:48:51 +08:00
private static final Logger logger = LoggerFactory.getLogger(Threads.class);
/**
* sleep等待,单位为毫秒
*/
2021-10-22 10:04:15 +08:00
public static void sleep(long milliseconds) {
try {
2020-02-13 10:48:51 +08:00
Thread.sleep(milliseconds);
2021-10-22 10:04:15 +08:00
} catch (InterruptedException e) {
2020-02-13 10:48:51 +08:00
return;
}
}
/**
* 停止线程池
* 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
* 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
* 如果仍然超時則強制退出.
2020-02-13 10:48:51 +08:00
* 另对在shutdown时线程本身被调用中断做了处理.
*/
2021-10-22 10:04:15 +08:00
public static void shutdownAndAwaitTermination(ExecutorService pool) {
if (pool != null && !pool.isShutdown()) {
2020-02-13 10:48:51 +08:00
pool.shutdown();
2021-10-22 10:04:15 +08:00
try {
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
2020-02-13 10:48:51 +08:00
pool.shutdownNow();
2021-10-22 10:04:15 +08:00
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
2020-02-13 10:48:51 +08:00
logger.info("Pool did not terminate");
}
}
2021-10-22 10:04:15 +08:00
} catch (InterruptedException ie) {
2020-02-13 10:48:51 +08:00
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
/**
* 打印线程异常信息
*/
2021-10-22 10:04:15 +08:00
public static void printException(Runnable r, Throwable t) {
if (t == null && r instanceof Future<?>) {
try {
2020-02-13 10:48:51 +08:00
Future<?> future = (Future<?>) r;
2021-10-22 10:04:15 +08:00
if (future.isDone()) {
2020-02-13 10:48:51 +08:00
future.get();
}
2021-10-22 10:04:15 +08:00
} catch (CancellationException ce) {
2020-02-13 10:48:51 +08:00
t = ce;
2021-10-22 10:04:15 +08:00
} catch (ExecutionException ee) {
2020-02-13 10:48:51 +08:00
t = ee.getCause();
2021-10-22 10:04:15 +08:00
} catch (InterruptedException ie) {
2020-02-13 10:48:51 +08:00
Thread.currentThread().interrupt();
}
}
2021-10-22 10:04:15 +08:00
if (t != null) {
2020-02-13 10:48:51 +08:00
logger.error(t.getMessage(), t);
}
}
}