即join()的作用是:
“等待该线程终止”,这里需要理解的就是该线程是指的主线程等待子线程的终止。也就是在子线程调用了join()方法后面的代码,只有等到子线程结束了才能执行。
public class JoinTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new ThreadA();// 利用多态实例化一个A线程
Thread t2 = new ThreadB(t1);// 利用多态实例化一个B线程
t1.start();
t2.start();
}
}
/* 继承于Thread的子类 */
class ThreadA extends Thread {
public void run() {
for (int i = 1; i <= 20; i++) {
System.out.println(i + " ¥¥¥");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
/* 继承于Thread的子类 */
class ThreadB extends Thread {
private Thread t;
public ThreadB() {
}
public ThreadB(Thread t) {
this.t = t;
}
public void run() {
for (int i = 1; i <= 20; i++) {
System.out.println(i + " ###");
try {
Thread.sleep(1000);
if (i == 10) {
t.join();
// 使这两个线程进入串行状态(也就是说t突然插了进来,必须等t执行完毕之后,才会让B线程继续执行)
}
} catch (InterruptedException e) {
}
}
}
}