美文网首页
ScheduleUtil 定时任务--线程池工具类

ScheduleUtil 定时任务--线程池工具类

作者: 颤抖的闪电 | 来源:发表于2017-09-25 00:37 被阅读0次

前言:因为公司的项目需求,需要做一个定时任务的功能,所以花了两天搞了个定时任务工具类,这是其中一个,还有个后台服务定时功能。核心类如下,先上个简单引用。

//1、待执行的线程类
ScheduleUtil.SRunnable sr = new ScheduleUtil.SRunnable() {
        @Override
        public void run() {
            System.out.println("Taskrepeating.a");
        }

        @Override
        public String getName() {
            return "a";
        }
    };
//2、启动
 System.out.println("启动周期线程...");
 ScheduleUtil.stard(sr, 1, 2, TimeUnit.SECONDS);
//3、停止
 System.out.println("停止周期线程");
 ScheduleUtil.stop(sr);
/**
 * @desc
 * @auth 方毅超
 * @time 2017/7/30 21:51
 */

public class ScheduleUtil {
    /*该接口定义了线程的名字,用于管理,如判断是否存活,是否停止该线程等等*/
    public interface SRunnable extends Runnable {
        String getName();
    }
    private static HashMap<String, ScheduledFuture> map = new HashMap<>();
    private static ScheduledExecutorService pool;

    public static void init() {
        pool = Executors.newScheduledThreadPool(3);
    }

    /**
     * @param sr     需要执行测线程,该线程必须继承SRunnable
     * @param delay  延迟执行时间
     * @param period 执行周期时间
     * @param unit   时间单位 比如TimeUnit.SECONDS
     */
    public static void stard(SRunnable sr, long delay, long period, TimeUnit unit) {
        if (sr.getName() == null || map.get(sr.getName()) != null) {
            throw new UnsupportedOperationException("线程名不能为空或者线程名不能重复!");
        }
        if (pool == null || pool.isShutdown()) init();
        ScheduledFuture scheduledFuture = pool.scheduleAtFixedRate(sr, delay, period, unit);
        map.put(sr.getName(), scheduledFuture);
    }

    /**
     * @param sr 停止当前正在执行的线程,该线程必须是继承SRunnable
     */
    public static void stop(SRunnable sr) {
        if (sr.getName() == null) {
            throw new UnsupportedOperationException("停止线程时,线程名不能为空!");
        }
        if (pool == null || pool.isShutdown()) return;//服务未启动
        if (map.size() > 0 && map.get(sr.getName()) != null) {
            map.get(sr.getName()).cancel(true);
            map.remove(sr.getName());
        }
        if (map.size() <= 0) {
            shutdown();
        }
    }

    /**
     * 停止所有线程服务
     */
    public static void shutdown() {
        map.clear();
        pool.shutdown();
    }

    /**
     * 判断该线程是否还存活着,还在运行
     *
     * @param sr
     * @return
     */
    public static boolean isAlive(SRunnable sr) {
        if (map.size() > 0 && map.get(sr.getName()) != null) {
            return !map.get(sr.getName()).isDone();
        }
        return false;
    }

}

相关文章

网友评论

      本文标题:ScheduleUtil 定时任务--线程池工具类

      本文链接:https://www.haomeiwen.com/subject/motrextx.html