我在线程中混淆了uisng连接方法 有人可以解释一下 我已经读过Parent Thread会等待它 子线程,直到孩子完成其操作
我有一个父线程,如下所示:
public class join implements Runnable {
public void run() {
System.out.println("Hi");
}
public static void main(String[] args) throws Exception {
join j1 = new join();
Thread parent = new Thread(j1);
child c = new child();
Thread child = new Thread(c);
parent.start();
child.start();
parent.join();
}
}
子线程:
public class child implements Runnable {
public void run() {
try {
Thread.currentThread().sleep(100000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("i m child");
}
}
执行此操作后,输出
您好
我是孩子
根据我的理解,它应该是相反的顺序
我是孩子
您好
如果我错了,请纠正我
答案 0 :(得分:5)
我读过父线程会等待其子线程
不,不是,
本声明:
parent.join();
将阻止当前线程(执行join
的线程)直到parent
完成。
实际上它根本不会影响parent
的执行。
我将用一个例子澄清:
class Test {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread() { public void run() {
System.out.println("t: going to sleep");
try { sleep(1000); } catch (InterruptedException e) { }
System.out.println("t: woke up...");
}};
System.out.println("main: Starting thread...");
t.start();
Thread.sleep(500);
System.out.println("main: sshhhh, t is sleeping...");
System.out.println("main: I'll wait for him to wake up..");
t.join();
System.out.println("main: Good morning t!");
}
}
输出(左边有时间):
0 ms: main: Starting thread...
0 ms: t: going to sleep
500 ms: main: sshhhh, t is sleeping...
500 ms: main: I'll wait for him to wake up..
1000 ms: t: woke up...
1000 ms: main: Good morning t!
答案 1 :(得分:1)
如果你改变了这个,你会得到预期的行为:
parent.start(); //Starts the parent
child.start(); //Starts the child
parent.join(); //Waits for the parent to finish, which doesn't do much since it's probably already done anyway.
到此:
child.start(); //Starts the child running
child.join(); //Waits for it to finish, which will take a long time
parent.start(); //Starts the parent running
答案 2 :(得分:1)
在您的情况下,您有三个主题:main,parent和child。 Main是jvm始终创建的初始线程,用于运行程序。父和子是在main中创建的两个线程。您将一个线程标记为父级是用词不当。它是没有其他线程的父级。相反,它是主要的孩子。加入是为了让一个线程在继续之前等待另一个线程完成执行。
一个假设的例子可能是服务员和厨师之间的关系。也就是说,服务员在厨师烹饪之前不能提供食物。所以服务员必须等到(加入)厨师才能完成食物。
public static void main(String[] args) {
Thread child = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("child doing its work");
}
});
child.start(); // start child thread
child.join(); // wait for child to finish
System.out.println("Now back in main. Child has finished its work");
}