Java-异步多线程专题-关闭线程池-打开线程池
package cn.jiangjiesheng.service.train.ExecutorTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ExecutorServiceOpenAndCloseTest {
private static Logger logger = LoggerFactory.getLogger(ExecutorServiceOpenAndCloseTest.class);
private static int AWAIT_TERMINATION_TIME = 120;//2min
private static int TASK_TIME = 10;
//openExecutorPoor 这种用法应该不合适,线程池正常情况下关闭后不能再执行任务,pool应该定义成final
//除非有非常特殊的场景需要这样用。
private static ExecutorService pool = openExecutorPoor(Executors.newFixedThreadPool(3));
public static void main(String[] args) {
pool.execute(new Runnable() {
@Override
public void run() {
try {
logger.info("开始执行线程池任务");
TimeUnit.SECONDS.sleep(TASK_TIME);
logger.info("执行线程池任务完成");
} catch (InterruptedException e) {
//如果线程池在TASK_TIME之前已经关闭了,会报如下异常
// java.lang.InterruptedException: sleep interrupted
// at java.lang.Thread.sleep(Native Method)
// at java.lang.Thread.sleep(Thread.java:340)
// at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
// at com.safety51.eduinp.service.train.ExecutorTest.ExecutorTest$1.run(ExecutorTest.java:27)
// at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
// at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
// at java.lang.Thread.run(Thread.java:748)
logger.error("执行线程池任务出现异常:{}", e.getMessage(), e);
}
}
});
closeExecutorPool(pool);
pool = openExecutorPoor(Executors.newFixedThreadPool(3));
pool.execute(new Runnable() {
@Override
public void run() {
try {
logger.info("开始再次执行线程池任务");
TimeUnit.SECONDS.sleep(TASK_TIME);
logger.info("再次执行线程池任务完成");
} catch (InterruptedException e) {
logger.error("再次执行线程池任务出现异常:{}", e.getMessage(), e);
}
}
});
}
private static ExecutorService openExecutorPoor(ExecutorService executorService) {
if(pool == null || pool.isShutdown() || pool.isTerminated()){
pool = executorService;
}
return pool;
}
private static void closeExecutorPool(ExecutorService pool) {
if (pool != null && !pool.isShutdown()) {
logger.info("开始关闭线程池");
pool.shutdown();
try {
if (!pool.awaitTermination(AWAIT_TERMINATION_TIME, TimeUnit.SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(AWAIT_TERMINATION_TIME, TimeUnit.SECONDS)) {
logger.error("线程池没有中断");
}
} else {
logger.info("线程池关闭成功");
}
} catch (InterruptedException ex) {
logger.error("线程异常关闭:{},将强制退出当前线程", ex.getMessage(), ex);
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
}
正文到此结束