| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package com.sqx.common.utils;
- import java.util.concurrent.*;
- import java.util.concurrent.atomic.AtomicInteger;
- import cn.hutool.core.exceptions.UtilException;
- /**
- * 全局公共线程池
- */
- public class MyGlobalThreadPool {
- private static ExecutorService executor;
- private MyGlobalThreadPool() {
- }
- static {
- init();
- }
- /**
- * 初始化全局线程池
- */
- synchronized public static void init() {
- if (null != executor) {
- executor.shutdownNow();
- }
- // executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
- executor = new ThreadPoolExecutor(20, 40, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000));
- }
- /**
- * 关闭公共线程池
- *
- * @param isNow 是否立即关闭而不等待正在执行的线程
- */
- synchronized public static void shutdown(boolean isNow) {
- if (null != executor) {
- if (isNow) {
- executor.shutdownNow();
- } else {
- executor.shutdown();
- }
- }
- }
- /**
- * 获得 {@link ExecutorService}
- *
- * @return {@link ExecutorService}
- */
- public static ExecutorService getExecutor() {
- return executor;
- }
- /**
- * 直接在公共线程池中执行线程
- *
- * @param runnable 可运行对象
- */
- public static void execute(Runnable runnable) {
- try {
- executor.execute(runnable);
- } catch (Exception e) {
- throw new UtilException(e, "Exception when running task!");
- }
- }
- /**
- * 执行有返回值的异步方法<br>
- * Future代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞
- *
- * @param <T> 执行的Task
- * @param task {@link Callable}
- * @return Future
- */
- public static <T> Future<T> submit(Callable<T> task) {
- return executor.submit(task);
- }
- /**
- * 执行有返回值的异步方法<br>
- * Future代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞
- *
- * @param runnable 可运行对象
- * @return {@link Future}
- * @since 3.0.5
- */
- public static Future<?> submit(Runnable runnable) {
- return executor.submit(runnable);
- }
- }
|