gpt4 book ai didi

java - 我不明白 Thread.sleep 和 'new' 运算符是如何工作的

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

有两件事我没有弄清楚,一个是关于 new 运算符,另一个是 Thread.sleep 方法。

// Create a second thread.
class NewThread implements Runnable {
Thread t;

NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread

try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}

我知道new操作符是用来分配一个对象的 例如:Box refvar=new Box(); 调用 Box 类的构造函数 在这种情况下调用是 new NewThread();

但是我没有引用变量,我不明白Java如何在没有引用变量的情况下调用构造函数。通常我使用:Nameofclass reference-variable-name = new NameOfConstructor();。

我不明白的另一件事是:如果没有名为 Thread 的对象,Java 如何调用 Thread.sleep()?在这种情况下应该是:t.sleep(1000) 还是不是?

提前致谢。

最佳答案

您可以调用构造函数而无需为其分配引用。

在您的情况下,字段 Thread t 维护对线程的引用,因此不会有过早的垃圾收集。

Thread.sleep() 使当前线程 hibernate ;即当前正在执行那段代码的线程。

关于java - 我不明白 Thread.sleep 和 'new' 运算符是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33829842/

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