【发布时间】:2021-02-28 19:15:38
【问题描述】:
我有这个递归创建线程的代码,但我似乎无法弄清楚它是如何阻止线程运行的。
public class Recursive_Thread {
public static void main(String[] args) {
int numThreads = 10;
/* create and start thread 0 */
System.out.println("Starting thread 0");
Thread thread = new Thread(new Inner(0, numThreads));
thread.start();
/* wait for thread 0 */
try {
thread.join();
} catch (InterruptedException e) {}
System.out.println("Threads all done");
}
/* inner class containing code for each thread to execute */
private static class Inner extends Thread {
private int myID;
private int limit;
public Inner(int myID, int limit) {
this.myID = myID;
this.limit = limit;
}
public void run() {
System.out.println("Hello World from " + myID);
/* do recursion until limit is reached */
if (myID == limit) {
System.out.println("Good Bye World from " + myID);
} else {
System.out.println("Starting thread " + (myID+1));
Thread thread = new Thread(new Inner((myID+1), limit));
thread.start();
try {
thread.join();
} catch (InterruptedException e) {System.out.println("Well... That didn't go as planned!");}
System.out.println("Thread " + (myID+1) + " finished");
System.out.println("Good Bye World from " + myID);
}
}
}
我运行了调试器,在打印第 10 个线程的消息后,执行似乎停止了这一行
System.out.println("Good Bye World from " + myID);
不知何故,执行又回到了这些行
System.out.println("Thread " + (myID+1) + " finished");
System.out.println("Good Bye World from " + myID);
对于第 10 个之后的每个剩余线程。我如何从
if (myID == limit) {
System.out.println("Good Bye World from " + myID);
到
else {
System.out.println("Starting thread " + (myID+1));
Thread thread = new Thread(new Inner((myID+1), limit));
thread.start();
try {
thread.join();
} catch (InterruptedException e) {System.out.println("Well... That didn't go as planned!");}
System.out.println("Thread " + (myID+1) + " finished");
System.out.println("Good Bye World from " + myID);
}
join 方法是否会创建某种检查点,让程序在完成所有 10 个线程的创建后返回?
【问题讨论】:
-
我不确定我是否完全理解您的要求。
-
对我来说也是如此,我尝试运行您的程序,输出正是我所期望的。你的问题是,为什么你在线程 10 之后得到
Good Bye World from的数字越来越少? -
对不起。我的问题应该更明显。执行顺序如何从打印再见世界到打印线程 10 完成?由于 if 语句为真,我如何进入 else 并仅执行 join 方法之后的行? join 方法是否会为程序创建一个检查点,以便在最后一个 start 方法执行完成后立即执行?
-
这一切的递归性在哪里?
-
@JayC667 我是 Java 和线程的新手,所以我正在研究我能找到的代码。这不是我的代码。因此,我不知道它是完全正确还是完全正确。
标签: java multithreading java-threads