一个线程可能需要另一个线程的结果,这是很常见的,例如,web浏览器在一个线程中加载html页面,他可能需要生成一个单独的线程来获取页面中的图片来嵌入到页面中。
那么加载html的这个线程,在结束页面的显示之前,可能必须等待加载到所有的图片。java提供了join方法来实现这种情况,它运行一个线程在继续执行前等待另一个线程结束。
这种方式在jdk1.5没有引入线程池和future接口之前常用,但是现在新的可以使用线程池和future实现。
public class JoinThreadTest {
public static void main(String[] args) throws InterruptedException {
int[] array = new int[10];
MaxArrayNum num= new MaxArrayNum(array);
num.start();
num.join();//如果不加上这个操作,则很可能出现数组越界异常
System.out.println("max 0:"+array[0]);
System.out.println("max 5:"+array[4]);
System.out.println("max 10:"+array[0]);
}
}
class MaxArrayNum extends Thread{
private int[] array;
public MaxArrayNum(int[] array){
this.array=array;
}
public void run(){
for(int i=0;i<10;i++){
this.array[i]=(int)( Math.random()*1000);
}
System.out.println(array[9]);
}
}