java的Thread.Join,是把指定的线程加入到当前线程,也就是如果调用了某个线程的join方法,则后续线程必须等待该线程执行完成后才能执行。
Thread name: t2
Thread name: t1
Thread name: t3
Thread name: t1
Thread name: t2
Thread name: t3
假设有三个线程,同时执行并输出当前线程的名称,输出后让线程sleep100毫秒,由于是并发执行,我们无法控制其输出的顺序,代码如下:
public class ThreadJoinDemo {
class MyThread extends Thread {
private String threadName;
public MyThread(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
System.out.println(threadName);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadJoinDemo.MyThread t1 = new ThreadJoinDemo().new MyThread("t1");
ThreadJoinDemo.MyThread t2 = new ThreadJoinDemo().new MyThread("t2");
ThreadJoinDemo.MyThread t3 = new ThreadJoinDemo().new MyThread("t3");
t1.start();
t2.start();
t3.start();
}
}
执行结果:
Thread name: t2
Thread name: t1
Thread name: t3
如果在每个线程启动后调用join方法,则后续线程必须等待该线程执行完成后才可以执行,就可以实现顺序输出的要求了。
public class ThreadJoinDemo {
class MyThread extends Thread {
private String threadName;
public MyThread(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
System.out.println("Thread name: " + threadName);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
ThreadJoinDemo.MyThread t1 = new ThreadJoinDemo().new MyThread("t1");
ThreadJoinDemo.MyThread t2 = new ThreadJoinDemo().new MyThread("t2");
ThreadJoinDemo.MyThread t3 = new ThreadJoinDemo().new MyThread("t3");
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
}
}
执行结果:
Thread name: t1
Thread name: t2
Thread name: t3