场景:启动一个线程,周期性的执行某一任务(状态检查)
1、定义状态检查类
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class StatusCheck
{
private ScheduledExecutorService threadPool;
//周期执行某一任务,线程池中开一个线程足矣s
private int threadNum = 1;
//第一次执行任务的延迟时间
private long initDelay = 0;
//执行周期
private long period = 5;
public void start()
{
//新建一个线程池
threadPool = Executors.newScheduledThreadPool(threadNum);
threadPool.scheduleAtFixedRate(new StatusCheckTask(), initDelay, period, TimeUnit.SECONDS);
}
//关闭线程池
public void stop()
{
if (null != threadPool)
{
threadPool.shutdown();
threadPool = null;
}
}
}
class StatusCheckTask implements Runnable
{
@Override
public void run()
{
//用”打印当前线程的名称“来模拟状态检查任务
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
}
}
2、测试类
public class ScheduledExecutorServiceTest
{
public static void main(String[] args)
{
StatusCheck checker = new StatusCheck();
checker.start();
checker.stop();
}
}