join方法的注解如下, 我的理解是,主线程不往下执行了直到调用join方法的子线程执行完毕或终止为止。注意,调用join方法只能控制子线程于主线程直接的执行顺序,并不能控制子线程之间的执行顺序,join里面的wait方法是主线程的,只会让主线程wait住。
/**
* Waits for this thread to die.
*/
定义一个类,继承Runnable 接口,该类可以根据传入构造函数的秒数睡多长时间。并且打印整个过程。
class Printer implements Runnable {
private String name = null;
private int time;
public Printer(String name,int time) {
this.name = name;
this.time=time;
}
public void run() {
System.out.println(this.name + " begin ...");
try {
Thread.sleep(1000 * time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name + " end ...");
}
}
测试join方法,启动2个线程后,分别调用线程的join方法。查看打印顺序。
public class JUC_003_Join {
public static void main(String args[]) throws InterruptedException {
Thread t1 = new Thread(new Printer("t1",1));
Thread t2 = new Thread(new Printer("t2",5));
t1.start();
t2.start();
t1.join();
System.out.println("t1 join is done ,main thread ...");
t2.join();
System.out.println("the end ...");
}
}
执行结果如下:
t2 begin ...
t1 begin ...
t1 end ...
t1 join is done ,main thread ...
t2 end ...
the end ...