gpt4 book ai didi

Java - 使用 wait() 方法直到达到特定时间

转载 作者:行者123 更新时间:2023-11-30 06:10:19 24 4
gpt4 key购买 nike

我有一个在我的程序后台运行的线程,它检测截止时间(由用户在程序开始时输入设置)何时发生。我在 while 循环中使用 sleep(1000) 方法实现了这一点。

一切正常,但我想将其从使用 sleep(1000) 更改为使用 wait()notifyAll() 与我的其余代码保持一致,并使警报实时发生,而不是延迟几分之一秒,直到线程重新唤醒。

这是我目前拥有的

    //Retrieve current date and time...
Calendar now = Calendar.getInstance();

//deadline not yet reached
while(now.before(deadline))
{
try
{
//wait a second and try again
sleep(1000);
}
catch (InterruptedException intEx)
{
//Do nothing.
}

//Update current date and time...
now = Calendar.getInstance();
//run loop again
}

////////////////////////////
///alert user of deadline///
////////////////////////////

我曾尝试将其更改为使用 wait(),但没有成功。任何人都可以找到一种方法来更改现有代码以实现我提到的方法吗?

提前致谢,标记

最佳答案

所以这个问题是,我如何使用wait来表现得像sleep。如果你想使用等待,你将不得不使用两个线程。使用ScheduledExecutorService (Tutorial)。

 ScheduledExecutorService executor = newSingleThreadScheduledExecutor();

这可以完成一次并重复使用。否则你必须关闭执行器。

我们将使用 Instant 将截止日期设置为 x 分钟后来自现代java.time框架(Tutorial)。

final Instant deadline = Instant.now().plus(x, ChronoUnit.MINUTES);

接下来我们要安排一个任务,以便我们的线程将在 x 分钟后唤醒。

while(Instant.now().isBefore(deadline)){
synchronized(deadline){
executor.schedule(
()->{
synchronized(deadline){
deadline.notifyAll();
}
},
Duration.between(Instant.now(),deadline).toMillis(),
TimeUnit.MILLISECONDS
);
deadline.wait();
}
}

它在一个循环中,以防万一有一个虚假的唤醒。它重新提交任务,以防出现虚假唤醒,同时另一个任务完成并且在线程再次调用 wait 之前没有唤醒线程。

上面这句话有点开玩笑。真的,如果您只是使用以下内容,它看起来会更“实时”。

long diff = deadline.getTimeInMillis()-now.getTimeInMillis();
if(diff>0)
Thread.sleep(diff);

关于Java - 使用 wait() 方法直到达到特定时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35975473/

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