gpt4 book ai didi

java - 在线程实例上使用 sleep(long) 的副作用

转载 作者:行者123 更新时间:2023-11-30 06:21:26 36 4
gpt4 key购买 nike

我尝试遵循简单的代码

public class HelloWorld {

public static void main(String args[]) throws InterruptedException {
System.out.println("hello World!");
new TestThread1().sleep(10);
}
}

class TestThread1 extends Thread{

}

但在 IDEA 中我得到了以下对话框。

enter image description here

看起来像一个错误,但问题是为什么会这样?在线程实例上调用 sleep(long) 有什么问题。

Thread.sleep(long) 也会在当前线程上调用 sleep 那么为什么我们不能直接这样做或者为什么不应该这样做呢?

public static native void sleep(long millis) throws InterruptedException;

javadocs 说

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

由于它是 Thread 类中的静态函数,我们应该能够从实例中调用它,因为实例具有类信息。它与本地方法有什么关系吗?

最佳答案

副作用是您创建了一个 Thread 实例(因此执行了 TestThread 类的构造函数中的所有内容)。规则是永远不要通过类实例访问或调用静态变量或方法。

然而,编译器优化了你的错误调用:

new TestThread().sleep(10);

编译成:

new TestThread(); // <---- This is the side effect!
Thread.sleep();

这就是您的 IDE 的建议:如果您真的想要这样,请明确地写出来,以便告诉我您知道自己在做什么。

关于java - 在线程实例上使用 sleep(long) 的副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20515382/

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