利用Executors.newSingleThreadScheduledExecutor()创建一个定时任务线程案例,其中利用CountDownLatch闭锁进行阻塞
Posted Acmen-zym
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用Executors.newSingleThreadScheduledExecutor()创建一个定时任务线程案例,其中利用CountDownLatch闭锁进行阻塞相关的知识,希望对你有一定的参考价值。
public static void main(String[] args) throws InterruptedException
CountDownLatch downLatch = new CountDownLatch(1);
Thread thread = Thread.currentThread();
AtomicInteger count = new AtomicInteger();//原子类统计
thread.setName("thread-1");//覆盖一下当前线程
String name = thread.getName();
Map<String, ScheduledFuture<?>> futureMap = new HashMap<>();
ScheduledFuture<?> scheduledFuture = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() ->
int andIncrement = count.getAndIncrement();
if (andIncrement == 5)
downLatch.countDown();
futureMap.get(name).cancel(true);
String format = LocalDateTime.now().atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss"));
System.out.println(format + " andIncrement = " + andIncrement);
//第一次执行间隔5秒,后续间隔三秒执行
, 5, 3, TimeUnit.SECONDS);
futureMap.put(name, scheduledFuture);
downLatch.await();//利用闭锁进行阻塞
System.out.println("scheduledFuture = " + scheduledFuture.isDone());
System.out.println("结束--------------");
以上是关于利用Executors.newSingleThreadScheduledExecutor()创建一个定时任务线程案例,其中利用CountDownLatch闭锁进行阻塞的主要内容,如果未能解决你的问题,请参考以下文章