概述

可以将两个交替执行的线程合并为顺序执行。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。(此处为常见面试考点)

join()让线程之间的执行变为了串行.

demo

FirstThread:

public class FirstThread extends Thread {

public FirstThread(String name) {
super(name);
}

@Override
public void run() {
for (int i = 0; i <= 20; i++) {
System.out.println(this.getName() + ":" + i);
}
}
}

SecondThread

public class SecondThread extends Thread {
public SecondThread(String name) {
super(name);
}

@Override
public void run() {
for (int i = 0; i <= 20; i++) {
System.out.println(this.getName() + ":" + i);
}
}
}

TestThread

public class TestThread {

public static void main(String[] args) throws InterruptedException {

FirstThread firstThread = new FirstThread("第一个线程");
SecondThread secondThread = new SecondThread("第二个线程");
firstThread.start();
/*
不加join()方法, 两个线程会交替执行
*firstThread线程加了join()之后 firstThread 线程会优先全部执行完secondThread线程才会执行
join()让线程之间的执行变为了串行.
* */
firstThread.join();
secondThread.start();


}

}