从头认识java-18.2 主要的线程机制(7)join

时间:2021-12-26 06:15:38

这一章节我们来讨论一下join。

1.什么是join?

阻塞当前线程,让.join的线程先做完。然后再继续当前线程

以下是api的解释:

A.join,在API中的解释是,阻塞当前线程B,直到A运行完毕并死掉,再运行B。

2.样例:

package com.ray.ch17;

public class Test {

	public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " start");
SleepThread sleepThread = new SleepThread("sleep");
Thread.sleep(2000);
JoinThread joinThread = new JoinThread(sleepThread, "join");
// joinThread.join();
System.out.println(Thread.currentThread().getName() + " end");
}
} class SleepThread extends Thread { public SleepThread(String name) {
super(name);
start();
} @Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println(getName() + " SleepThread");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} class JoinThread extends Thread { private SleepThread sleepThread; public JoinThread(SleepThread sleepThread, String name) {
super(name);
this.sleepThread = sleepThread;
start();
} @Override
public void run() {
try {
System.out.println(getName() + " join start");
sleepThread.join();
System.out.println(getName() + " join end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

输出:

main start
sleep SleepThread
sleep SleepThread
sleep SleepThread
main end
join join start
sleep SleepThread
sleep SleepThread
join join end

package com.ray.ch17;

public class Test {

	public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " start");
SleepThread sleepThread = new SleepThread("sleep");
Thread.sleep(2000);
JoinThread joinThread = new JoinThread(sleepThread, "join");
joinThread.join();
System.out.println(Thread.currentThread().getName() + " end");
}
} class SleepThread extends Thread { public SleepThread(String name) {
super(name);
start();
} @Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println(getName() + " SleepThread");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} class JoinThread extends Thread { private SleepThread sleepThread; public JoinThread(SleepThread sleepThread, String name) {
super(name);
this.sleepThread = sleepThread;
start();
} @Override
public void run() {
try {
System.out.println(getName() + " join start");
sleepThread.join();
System.out.println(getName() + " join end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

输出:

main start
sleep SleepThread
sleep SleepThread
sleep SleepThread
join join start
sleep SleepThread
sleep SleepThread
join join end
main end

上面两个代码的不同主要是体如今joinThread.join();是否被凝视。

对照上面的两个代码的输出,主要不同在于main end 的位置。当joinThread.join();的时候,因为须要先阻塞main方法的线程,先完毕joinThread所在线程,因此main end的位置会出现上面的变化。

还有一方面。我们从sleep和join两个线程输出的文字的位置也能够推导出上面的结论。

总结:这一章节我们简介了一下join。

这一章节就到这里,谢谢。

-----------------------------------

文件夹