Thread定义了一个join方法,允许当前线程在另一个线程上等待,直到该线程结束工作(当前线程会等待调用join()方法的线程执行完后才开始)。 通常是用来协调两个线程工作使用
package test2;
public class ThreadTest1 {
static boolean flage = false;
public static void main(String[] args) {
final Thread threada = new Thread() {
public void run() {
System.out.println("开始下载");
for (int i = 0; i <= 100; i++) {
System.out.println("下载" + i + "%");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("下载完成");
flage = true;
};
};
Thread threadb = new Thread() {
public void run() {
try {
// threadb线程中调用threada.join(),则当前线程等threada线程执行完后才开始
// 屏蔽threada.join(),两个线程同时进行,将会抛出自定义异常
threada.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("开始显示图片");
if (flage) {
System.out.println("显示图片");
} else {
throw new RuntimeException("下载错误");
}
};
};
threada.start();
threadb.start();
}
}