gpt4 book ai didi

java - Thread.sleep 行为异常

转载 作者:行者123 更新时间:2023-12-01 18:50:14 24 4
gpt4 key购买 nike

我有以下代码:

public Move chooseMove(Board board) {

// start parallel thread
this.tn = new TreeNode(this.myboard, this, null);
tn.stop = false;
this.curT = (new Thread(tn));
this.curT.start();


try {
long startTime = System.currentTimeMillis();
Thread.sleep(4000 );
System.out.println(System.currentTimeMillis() - startTime);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
tn.stop=true;
return getBestMove();
}
}

输出有时是一个远远大于 4000 毫秒(如 5400 毫秒)的值,这意味着线程的 hibernate 时间超过了应有的时间。有什么帮助吗?谢谢。

编辑:据我所知,不能保证 Thread#sleep 在指定的延迟后精确停止。然而,额外的 1400ms 是一个很长的延迟。基本上,我正在实现一个游戏玩家代理,我需要一种方法来运行任务,然后在 5 秒后将值返回到服务器(否则服务器结束游戏)。服务器正在使用 java.util.Timer.schedule(TimerTask 任务,长延迟)。只有一个线程与主线程并行运行,即上面代码中的 this.curT,因此并没有真正繁重的多线程处理。

最佳答案

来自docs.oracle.com :

Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.

关于java - Thread.sleep 行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16135328/

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