java - Thread.sleep 行为异常

标签 java multithreading concurrency thread-sleep

我有以下代码:

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/

相关文章:

http - Golang,零指针取消引用或无效内存地址

java - 使用警报对话框从内部类访问变量

java - 在 Java 中存储 Web 爬虫的 URI 的最有效的数据结构

c# - C# 中的空合并运算符 (??) 是线程安全的吗?

mongodb - MongoDB 将写入锁定到什么级别? (或 : what does it mean by "per connection"

java - 有效不可变对象(immutable对象)

java - 显示带有小数点的百分比的格式

java - Shell 脚本调用 java 可执行文件并捕获异常

multithreading - 如何将线程函数的地址作为回调传递给winapi?

c - Tcl 和 C 线程之间的共享变量