gpt4 book ai didi

java - 为什么调用 join 方法时主线程消失了?

转载 作者:行者123 更新时间:2023-12-02 03:20:53 25 4
gpt4 key购买 nike

根据 Thread.State.TIMED_WAITING 的 Javadoc ,我写了代码:

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

public class TestJoin {

public static void main(String[] args) throws InterruptedException {
ThreadUtil.printThreadState("main", "car", "dog");

Thread carThread = new Thread(() -> {
System.out.println(LocalDateTime.now() + " Car run");
long now = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - now > 3000) {
break;
}
}
System.out.println(LocalDateTime.now() + " Car Stop");
}, "car");

Thread dogThread = new Thread(() -> {
System.out.println(LocalDateTime.now() + " Dog run");
long now = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - now > 3000) {
break;
}
}
System.out.println(LocalDateTime.now() + " Dog Stop");
}, "dog");

try {
dogThread.start();
carThread.start();

System.out.println("Begin join");
carThread.join(3);
System.out.println("endjoin");
} catch (Exception e) {
e.printStackTrace();
}
}}

import java.time.LocalDateTime;

public class ThreadUtil {

public static void printThreadState(String... filter) {
Thread print = new Thread(() -> {
long now = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - now > 1000) {
now = System.currentTimeMillis();
Thread.getAllStackTraces().forEach((key, thread) -> {
for (int i = 0; i < filter.length; i++) {
if (key.getName().equals(filter[i])) {
System.out.println(LocalDateTime.now() + " " +key.getName() + " -> " + key.getState());
}
}
});
}
}
}, "Print");
print.start();
}
}

输出为

Begin join
end join
2016-09-22T18:01:53.484 Car run
2016-09-22T18:01:53.498 Dog run
2016-09-22T18:01:54.460 dog -> RUNNABLE
2016-09-22T18:01:54.460 car -> RUNNABLE
2016-09-22T18:01:55.531 dog -> RUNNABLE
2016-09-22T18:01:55.532 car -> RUNNABLE
2016-09-22T18:01:56.461 dog -> RUNNABLE
2016-09-22T18:01:56.462 car -> RUNNABLE
2016-09-22T18:01:56.486 Car Stop
2016-09-22T18:01:56.499 Dog Stop

就像那个文档一样,主线程状态是“TIMED_WAITING”,但它消失了,主线程在哪里?

PS:当我写的时候

carThread.join();

出现了

Begin join
2016-09-22T18:04:31.583 Dog run
2016-09-22T18:04:31.584 Car run
2016-09-22T18:04:32.543 main -> WAITING
2016-09-22T18:04:32.543 dog -> RUNNABLE
2016-09-22T18:04:32.543 car -> RUNNABLE
2016-09-22T18:04:33.604 main -> WAITING
2016-09-22T18:04:33.604 dog -> RUNNABLE
2016-09-22T18:04:33.604 car -> RUNNABLE
2016-09-22T18:04:34.585 Car Stop
end join
2016-09-22T18:04:34.608 Dog Stop
2016-09-22T18:04:34.608 dog -> TERMINATED

最佳答案

因为没有 join 你的主线程会先于其他线程完成。 join 使主线程“等待”,直到调用 join 的线程完成,直到那时为止阻塞。

关于java - 为什么调用 join 方法时主线程消失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39636151/

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