gpt4 book ai didi

java - 我的倒计时只减 1 就不再减了,这是为什么?

转载 作者:行者123 更新时间:2023-12-02 09:07:26 24 4
gpt4 key购买 nike

所以,我想在服务类中为用户输入的日期创建一个倒计时。现在我在倒计时方面遇到了问题。似乎无论如何它只减去 1 秒并且不会进一步。这是代码:

倒计时的逻辑

package com.example.service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CounterService {
LocalDateTime dateTime;

public LocalDateTime getDateTime(){
return dateTime;
}

public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}

public LocalDateTime parseDate(String eventDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
dateTime = LocalDateTime.parse(eventDate, formatter);
return dateTime;
}


public static void main(String[] args) {

CounterService cs = new CounterService();
LocalDateTime a = LocalDateTime.of(2021,11,11,21,43,44);
cs.setDateTime(a);

Runnable r = new Counter(cs);
new Thread(r).start();

}
}

和可运行的

package com.example.service;

import java.time.LocalDateTime;

public class Counter implements Runnable {
CounterService counter;

public Counter(CounterService cs) {
this.counter = cs;
}

public void setCounter(CounterService cs) {
this.counter = cs;
}

public void run() {
LocalDateTime countFromThisDate = counter.getDateTime();
try {
boolean x = true;
while (x) {
LocalDateTime substracting = countFromThisDate.minusSeconds(1);
Thread.sleep(1000);
System.out.println(substracting);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}

另外,我如何添加这个计数器(在它工作后),以便它动态刷新并逐一减去每一秒?

最佳答案

这里声明一个实现缺陷 - Thread.sleep 不能保证线程在耗时间隔后运行,它只是在时间间隔后使线程状态准备(由 cpu 运行) 。相反,您应该使用系统时间来获取自计数器启动以来耗时。

--更新--

对 CounterService 进行一点小改动即可完成工作。除了倒计时日期时间之外,CounterService 还将保留一个开始时间。代码如下所示 -

class CounterService {      

private LocalDateTime dateTime;

private LocalDateTime startTime;

public CounterService(LocalDateTime dateTime, LocalDateTime startTime) {
this.dateTime = dateTime;
this.startTime = startTime;
}

public LocalDateTime getCounterTime() {
return dateTime.minusSeconds(startTime.until(LocalDateTime.now(), ChronoUnit.SECONDS));
}

public static void main (String[] args) throws java.lang.Exception {
LocalDateTime a = LocalDateTime.of(2021,11,11,21,43,44);
LocalDateTime startTime = LocalDateTime.now();

final CounterService counterService = new CounterService(a, startTime);

new Thread(() -> {
while (true) {
System.out.println(counterService.getCounterTime());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}

关于java - 我的倒计时只减 1 就不再减了,这是为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59700459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com