Overview
You can merge two alternately executed threads into sequential execution. For example, the Join() method of thread A is called in thread B, and thread B will not continue to execute until thread A is executed. (This is a common interview test site)
join() makes the execution between threads become serial.
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();
}
}