Demo
package com.wjz.executor;
public class ExecutorDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorScheduler scheduler = new ExecutorScheduler();
scheduler.execute();
Thread.sleep(60 * 60 * 1000);
}
}
自定义Runnable,类似于定时任务
package com.wjz.executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ExecutorScheduler implements Runnable {
private static final String threadNamePrefix = "SessionValidationThread-";
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 任务调度喽......");
}
public void execute() {
// ScheduleExecutorService代表可在指定延迟或周期性执行线程任务的线程池
ScheduledExecutorService threadPool = Executors
// 创建只有一条线程的线程池,支持在指定延迟后执行线程任务
.newSingleThreadScheduledExecutor(new ThreadFactory() {
private final AtomicInteger count = new AtomicInteger(1);
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
// 后台程序
thread.setDaemon(true);
thread.setName(threadNamePrefix + count.getAndIncrement());
return thread;
}
});
// runnable, 初始延迟, 周期间隔, 时间单位
threadPool.scheduleAtFixedRate(this, 2 * 1000L, 1 * 1000L, TimeUnit.MILLISECONDS);
}
}