我很困惑在线程中的uisng连接方法可以有人请解释我已经读过父线程将等待其子线程,直到子完成其操作
我有一个父线程,如下所示:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
儿童线程:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
执行此操作后,输出为
你好
我的孩子
根据我的理解,它应该是相反的顺序
我的孩子
你好
如果我错了,请纠正我
我已经读过Parent Thread会等待它的子Thread
不,不是真的,
这个说法:
parent.join();
Run Code Online (Sandbox Code Playgroud)
将阻塞当前线程(执行该线程的线程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!");
}
}
Run Code Online (Sandbox Code Playgroud)
输出(左边的时间):
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!
Run Code Online (Sandbox Code Playgroud)