gpt4 book ai didi

java - 使用 CountDownTimer() 比直接使用 System.currentTimeMillis() 有任何优势

转载 作者:行者123 更新时间:2023-11-30 09:17:30 25 4
gpt4 key购买 nike

我有几个需要同时运行的计时器。我知道 CountDownTimer 在进入最终确定阶段 [onFinish()] 时会出现问题,有时它会提前一点完成,但对其中一个的优点/缺点了解不多。直接调用 System.currentTimeMillis() 必须更轻便,但 CountDownTimer 必须具有某种优势,而不仅仅是易用性,不是吗?

例如,类似的东西

long totalTime = 30000;
long startTime = System.currentTimeMillis();
long currTime = System.currentTimeMillis();
while(totalTime > startTime - currTime){
currTime = System.currentTimeMillis();
}
System.out.println("Finished!");

最佳答案

CountDownTimer 的主要优点是您会在倒计时期间定期收到通知。这些通知提供了一种简单的方法来 react 性响应剩余时间,而不是主动调用 System.currentTimeMillis(),这可能需要一些无论如何,某种计时器机制。 CountDownTimer 代表您进行计时器设置、回调和清理。

您的示例代码将使 CPU 非常忙碌(从而消耗更多的电池生命周期)而没有任何好处。如果代码在主线程上运行,它还会使应用程序的 UI 无响应。另一方面,CountDownTimer 不会使 UI 停止,只会在执行通知时消耗 CPU 时间。从性能和易用性的角度来看,使用 CountDownTimer 是正确的选择。

关于java - 使用 CountDownTimer() 比直接使用 System.currentTimeMillis() 有任何优势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18934948/

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