gpt4 book ai didi

Java 线程编程示例 - 程序运行异常

转载 作者:行者123 更新时间:2023-11-29 03:50:38 25 4
gpt4 key购买 nike

我正在阅读 Paul Hyde 所著的Java 线程编程一书。我正在阅读第一章。我在 Eclipse IDE 中运行各种示例程序。

public class TwoThreadAlive extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}

public void printMsg() {
// get a reference to the thread running this
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}

public static void main(String[] args) {
TwoThreadAlive tt = new TwoThreadAlive();
tt.setName("my worker thread");

System.out.println("before start(), tt.isAlive()=" + tt.isAlive());
tt.start();
System.out.println("just after start(),tt.isAlive()=" + tt.isAlive());

for (int i = 0; i < 10; i++) {
tt.printMsg();
}

System.out
.println("at the end of main(), tt.isAlive()=" + tt.isAlive());
}}

这个程序每次运行时都会给出SAME输出。但是它提到输出会有所不同,因为JVM会忙于上下文切换。你能告诉我为什么它会给出相同的输出吗输出?

它正在给予

at the end of main(), tt.isAlive()=true

这应该是

at the end of main(), tt.isAlive()=false

请帮帮我,这让我很生气。

最佳答案

不,输出是正确的,因为到 main 方法执行最后一个 println 时,无法保证您的线程也已完成执行。在最后一个打印之前添加 tt.join();:

tt.join();

System.out
.println("at the end of main(), tt.isAlive()=" + tt.isAlive());

现在主线程将被阻塞,直到 tt 完成,因此 println 将仅在 tt 结束后执行。

至于您的输出始终相同,10 是一个太细的粒度值,很可能每个线程在上下文切换时完成打印所有内容。尝试使用更大的值。

关于Java 线程编程示例 - 程序运行异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8970433/

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