gpt4 book ai didi

Java线程join()混淆

转载 作者:行者123 更新时间:2023-11-29 09:59:01 29 4
gpt4 key购买 nike

我试图按照这个例子来理解 join() 方法:

class PrintDemo {

public void printCount() {

try {

for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}

class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;

ThreadDemo(String name, PrintDemo pd) {
threadName = name;
PD = pd;
}

public void run() {

synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {
System.out.println("Starting " + threadName );

if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {
PrintDemo PD = new PrintDemo();

ThreadDemo T1 = new ThreadDemo("Thread - 1 ", PD);
ThreadDemo T2 = new ThreadDemo("Thread - 2 ", PD);

T1.start();
T2.start();

// wait for threads to end
try {
T1.join();
T2.join();
} catch (Exception e) {
System.out.println("Interrupted");
}
}
}

我了解到 T1.join() 例如让主线程等待 T1 完成以继续其流程。我在这里正确吗?

所以,我修改了如下代码:

      System.out.println("1");
T1.start();
System.out.println("2");
T2.start();

// wait for threads to end
try {
System.out.println("3");
T1.join();
System.out.println("4");
T2.join();
System.out.println("5");
} catch (Exception e) {
System.out.println("Interrupted");
}

为了尝试并遵循完整的流程。

这是我每次得到的:

1
Starting Thread - 1
2
Starting Thread - 2
3
4
5
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.

我无法解释...

为什么计数器打印在“5”字符之后???我可能不太了解加入问题...

最佳答案

您启动一个线程 (A),该线程 (A) 启动另一个线程 (B)。

您等待线程 A 完成 - 这几乎是立即完成的,因为它除了启动线程 B 之外几乎不做任何事情 - 但线程 B 仍在独立运行。

关于Java线程join()混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48644114/

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