利用JDK提供的ScheduledThreadPoolExecutor来执行周期性任务

·  阅读 79
  1. 提供一个线程工厂
public class ThreadFactoryImpl implements ThreadFactory {
    private final AtomicLong threadIndex = new AtomicLong(0);
    private final String threadNamePrefix;
    private final boolean daemon;

    public ThreadFactoryImpl(final String threadNamePrefix) {
        this(threadNamePrefix, false);
    }

    public ThreadFactoryImpl(final String threadNamePrefix, boolean daemon){
        this.threadNamePrefix = threadNamePrefix;
        this.daemon = daemon;
    }
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, this.threadNamePrefix + this.threadIndex.incrementAndGet());
        thread.setDaemon(daemon);
        return thread;
    }
}
复制代码

2.创建任务类

public class DefaultMessageStore {
    private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryImpl("StoreScheduledThread")
    );

    private final AtomicLong i = new AtomicLong(0);

	/**
     * 延时5秒开始执行,每2秒执行一次
     */
    public void start() {
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("还是说会话" + i.incrementAndGet());
            }
        }, 5, 2, TimeUnit.SECONDS);
    }

    /**
     * 终止周期性任务的执行
     */
    public void stop() {
        scheduledExecutorService.shutdown();
    }
}
复制代码

3.测试

public class Test {
	public static void main(String[] args) {
        DefaultMessageStore messageStore = new DefaultMessageStore();
        messageStore.start();
    }
}
复制代码
分类:
后端
标签:
分类:
后端
标签: