join方法主要用于线程的优先运行,当有N个线程同时运行时,其中有一个线程只要调用join方法,其他所有的线程包括主线程都暂停运行,都让该线程先运行完过后再来运行。
class ThreadJoin extends Thread {
@Override
public void run() {
for (int i = 0; i < 40; i++) {
try {
Thread.sleep(30);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(getName() + "----" + i);
}
}
}
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
ThreadJoin t1 = new ThreadJoin();
ThreadJoin t2 = new ThreadJoin();
t1.start();
t1.join(); // 让其他线程等待,只有当前线程执行完毕,才会唤醒。
t2.start();
for (int i = 0; i < 40; i++) {
System.out.println("main----" + i);
}
}
}
这里可以发现t1线程首先运行完毕
然后main线程和t2线程才会运行!join方法就是这么简单