之前我的线程两篇文章用了join()而没有详细说明有什么用~今天就来说下join()的作用。
join()就是使异步执行的线程变成同步执行。也就是说,当调用线程实例start()后这个方法立即返回。如果在调用start()后需要使用一个由这个线程计算得到的值,就必须使用join()方法。使用join()才能保证start()方法后面的某条语句在线程执行后执行。
下面代码演示:
public class ThreadJoin extends Thread{
public static int num = 0;
public static synchronized void numAdd(){
num++;
}
@Override
public void run() {
for (int i = 0; i <10; i++) {
numAdd();
try {
sleep(3);//为了准确性
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread threads[] = new Thread[100];
for(int i = 0;i<threads.length;i++){
threads[i] = new ThreadJoin();
}
for(int i = 0;i<threads.length;i++){
threads[i].start();
}
for(int i = 0;i<threads.length;i++){
threads[i].join();
}
System.out.println("n="+ThreadJoin.num);
}
}