Java异步编程

1、Java基本的异步工具类设计:

1、任务执行容器

public static synchronized ExecutorService getPoolExecutor() {
        if(executor==null) {
            BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10000);
            executor = new ThreadPoolExecutor(8,8,0L, TimeUnit.MILLISECONDS,queue,
                    new ThreadPoolExecutor.DiscardOldestPolicy());
        }
        return executor;
    }

2、初始化

主要初始化的是log

public static void init() {
        monitor = new Thread(new MyMonitorThread((ThreadPoolExecutor) getPoolExecutor(), 600));
        monitor.start();
        log.info("---------------NewOpt ThreadPoolManager init success!----------------", "");
    }

3、销毁

 public void close() {
        try {
            getPoolExecutor().shutdown();
            if(monitor!=null && monitor.isAlive()) {
                monitor.interrupt();
            }
        } catch (Exception e) {

        }
    }

4、基于线程的监视器

static  class  MyMonitorThread implements Runnable {

        private ThreadPoolExecutor executor;
        private int seconds;
        private boolean isRun = true;
        public MyMonitorThread(ThreadPoolExecutor executor,int delay) {
            this.executor = executor;
            this.seconds = delay;
        }
        public void shutdown() {
            this.isRun = false;
        }
        @Override
        public void run() {
            while(isRun) {
                log.info(log.getParamsBuilder().addParam("NewOpt",String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
                        this.executor.getPoolSize(), this.executor.getCorePoolSize(),
                        this.executor.getActiveCount(), this.executor.getCompletedTaskCount(),
                        this.executor.getTaskCount(), this.executor.isShutdown(), this.executor.isTerminated())).build());
                try {
                    Thread.sleep(seconds*1000);
                }catch (InterruptedException e) {
                    log.error();
                }
                if (this.executor.isShutdown()){
                    shutdown();
                }
            }
        }
    }

单独创建线程能够监控整体异步任务执行情况,初始化与销毁保证整个生命周期都在监控下

5、执行

  //执行单个不需要返回的任务
  public static void executeTask(Runnable command) {
        try {
            getPoolExecutor().execute(command);
        }catch (Exception e) {

        }
    }
   //执行单个需要返回的任务
    public static Future executeCallable(Callable command) {
        try {
            return getPoolExecutor().submit(command);
        }catch (Exception e) {
            return null;
        }
    }
   //批量执行任务
    public static <T> List<Future<T>> invokeAll(Connection<? extends Callable<T>> tasks) {
        try {
            return getPoolExecutor().invokeAll(tasks);
        }catch (Exception e) {
            return null;
        }
    }
/**
 * @author jh.pei
 * @date 2021/4/12 16:32
 */
public class PjhThreadPoolManager {
    private static log = LoggerWrapperFactory.getLoggerWrapper(PjhThreadPoolManager.class);

    private static Thread monitor = null;

    private static ExecutorService executor;

    public static void init() {
        monitor = new Thread();
        monitor.start();
    }

    public static synchronized ExecutorService getPoolExecutor() {
        if(executor==null) {
            BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10000);
            executor = new ThreadPoolExecutor(8,8,0L, TimeUnit.MILLISECONDS,queue,
                    new ThreadPoolExecutor.DiscardOldestPolicy());
        }
        return executor;
    }

    public static void executeTask(Runnable command) {
        try {
            getPoolExecutor().execute(command);
        }catch (Exception e) {

        }
    }
    public static Future executeCallable(Callable command) {
        try {
            return getPoolExecutor().submit(command);
        }catch (Exception e) {
            return null;
        }
    }
    public static <T> List<Future<T>> invokeAll(Colloection<? extends Callable<T>> tasks) {
        try {
            return getPoolExecutor().invokeAll(tasks);
        }catch (Exception e) {
            return null;
        }
    }
    public void close() {
        try {
            getPoolExecutor().shutdown();
            if(monitor!=null && monitor.isAlive()) {
                monitor.interrupt();
            }
        } catch (Exception e) {

        }
    }
    static  class  MyMonitorThread implements Runnable {

        private ThreadPoolExecutor executor;
        private int seconds;
        private boolean isRun = true;
        public MyMonitorThread(ThreadPoolExecutor executor,int delay) {
            this.executor = executor;
            this.seconds = delay;
        }
        public void shutdown() {
            this.isRun = false;
        }
        @Override
        public void run() {
            while(isRun) {
                log.info(log.getParamsBuilder().addParam("NewOpt",String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
                        this.executor.getPoolSize(), this.executor.getCorePoolSize(),
                        this.executor.getActiveCount(), this.executor.getCompletedTaskCount(),
                        this.executor.getTaskCount(), this.executor.isShutdown(), this.executor.isTerminated())).build());
                try {
                    Thread.sleep(seconds*1000);
                }catch (InterruptedException e) {
                    log.error();
                }
                if (this.executor.isShutdown()){
                    shutdown();
                }
            }
        }

    }
}

二、基于springBoot的异步工具类设计:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值