gpt4 book ai didi

Java 线程 : Calling run() method on the Thread object after start()

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

我看到了有趣的行为。我正在运行这段代码

public class ThreadsTest {

public static void main(String[] args) {
Runnable mr = new MyRunnable();
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);
t1.setName("first");
t2.setName("second");
t1.start();
t2.start();
t1.run();
}
}

class MyRunnable implements Runnable {
public void run() {
for (int i=0; i < 2; i++) {
System.out.println("Running: " + Thread.currentThread().getName());
}
}
}

我得到的输出是:

Running: first
Running: first
Running: second
Running: second

我期待看到类似这样的东西:

Running: first
Running: first
Running: second
Running: second
Running: main
Running: main

有谁知道为什么我在输出的某处看不到Running: main。谢谢。

最佳答案

这个解释有点微妙。

Thread.run() 方法的默认行为被描述为运行提供的 Runnable(如果存在),否则不执行任何操作。

微妙之处在于,当线程退出时,exit() 方法“主动”清空引用字段以防止存储泄漏。 (这里是 the source ... 从第 720 行开始。)看起来当您在 main 中调用 t1.run() 时,线程已经退出,因此调用是空操作。

当然,输出取决于 main 线程是否在子线程退出之前再次运行……这将取决于您的平台;例如JVM 和操作系统级线程调度程序做什么以及有多少个内核可用。

关于Java 线程 : Calling run() method on the Thread object after start(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14794613/

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