thread.join()是让当前线程block住,等thread执行完之后,再继续执行 。比如有3个线程在执行计算任务,必须等三个线程都执行完才能汇总,那么这时候在主线程里面让三个线程join,最后计算结果既可,代码显示如下:
package chapter01;
import java.util.Random;
//thread.join()用于停止当前线程而运行别的线程
public class Thread_Join_Test {
public static void main(String[] args) {
System.out.println("in " + Thread.currentThread().getName());
long start = System.currentTimeMillis();
CounterThread[] ct = new CounterThread[3];
for (int i = 0; i < ct.length; i++) {
ct[i] = new CounterThread();
ct[i].start();
try {
ct[i].join();//让当前线程block住,等thread执行完之后,再继续执行 。
} catch (Exception e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println("join total time = " + (end - start)+"ms!");
int result = 0;
for (int j = 0; j < ct.length; j++) {
result += ct[j].getResult();
}
System.out.println("the result is " + result);
}
}
class CounterThread extends Thread {
public CounterThread() {
}
private int result;
public int getResult() {
return result;
}
public void run() {
try {
int time = (new Random().nextInt() >>> 1) % 5000;//取int范围内的一个随机数,然后无符号右移1次(除以2)。m>>> n=m/2ⁿ
Thread.sleep(time);
System.out.println(Thread.currentThread().getName() + " is blocked for " + time + "ms");
} catch (InterruptedException ex) {
}
result = 5;
}
}
测试结果:
in main
Thread-0 is blocked for 2955ms
Thread-1 is blocked for 2761ms
Thread-2 is blocked for 2568ms
join total time = 8287ms!
the result is 15