thread.join() 方法的解释是 "Waits for this thread to die",即"等待这个线程死亡",比如 threadxxx.join() 时就是"等待 线程xxx 死亡",当然这句话时缺少一个主语的,谁等待?是执行这句代码的线程等待,比如在main 方法中有 threadxxx.join() ,就是说主线程会等待线程xxx死亡后再向下执行 threadxxx.join()之后的代码, 对于新手来说,感觉怪怪的,有一个例子可以体会该方法的价值。想必大家都会写计算一个方法执行时间的代码吧,无非是得到起止的时间差,可是在多线程环境下,该方法未必奏效,比如:
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
for( int i=0;i<10;i++ ){
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getId() + " start...");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId() + " stop...");
}
}).start();
}
long t2 = System.currentTimeMillis();
System.out.println( "take " + ( t2-t1 ) + " milliseconds" );
}
这种方法对吗?当执行到最后一句时,可能有的线程还未执行完,所以不对,知识后就用到join了,看看join的定义,在这里就是当所有的线程执行完之后主方法在执行,下面是正确做法:
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
List<Thread> threads = new ArrayList<>();
for( int i=0;i<10;i++ ){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getId() + " start...");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId() + " stop...");
}
});
thread.start();
threads.add( thread );
}
for( Thread thread:threads ){
try {
thread.join();
}catch (Exception e){
e.printStackTrace();
}
}
long t2 = System.currentTimeMillis();
System.out.println( "take " + ( t2-t1 ) + " milliseconds" );
}