gpt4 book ai didi

java - 线程的Join方法

转载 作者:行者123 更新时间:2023-12-02 05:49:41 29 4
gpt4 key购买 nike

我注意到 Join 方法的有趣行为非常令人困惑,多线程可能已经过时且过时(在 java 8 的 lambda/streams 之后),但仍然好奇地想知道我是否遗漏了某些东西,永远不会在实时项目中使用线程。

class JoinDemoThread1 implements Runnable {
String threadName;

@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Testing in demothread1=" + i);
}
}
}
<小时/>
class JoinDemoThread2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Testing in demothread2=" + i);
}
}
}
<小时/>
public class JoinDemo {
public static void main(String args[]) {
JoinDemoThread1 joinDemoThread1 = new JoinDemoThread1();
JoinDemoThread2 joinDemoThread2 = new JoinDemoThread2();

Thread demoThread1 = new Thread(joinDemoThread1);
Thread demoThread2 = new Thread(joinDemoThread2);

demoThread1.start();
demoThread2.start();

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

System.out.println("Ending Main program.");
}
}

最佳答案

运行给定代码时的输出:

Testing in demothread1=0
Testing in demothread1=1
Testing in demothread1=2
Testing in demothread1=3
Testing in demothread1=4
Testing in demothread2=0
Testing in demothread2=1
Testing in demothread2=2
Testing in demothread2=3
Testing in demothread2=4
Ending Main program.

当然,看起来根本没有多线程发生。这是因为您的线程完成得如此之快,以至于调度程序没有理由交错线程。如果有更密集的过程,您将看到更预期的输出。

例如,稍微延迟线程时:

class JoinDemoThread2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {}
System.out.println("Testing in demothread2=" + i);
}
}
}

输出将是:

Testing in demothread2=0
Testing in demothread1=0
Testing in demothread1=1
Testing in demothread2=1
Testing in demothread1=2
Testing in demothread2=2
Testing in demothread1=3
Testing in demothread2=3
Testing in demothread1=4
Testing in demothread2=4
Ending Main program.

关于java - 线程的Join方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56061367/

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