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闭锁进行阻塞
最新推荐文章于 2024-03-26 11:05:05 发布