join用于主线程等待子线程运行完毕它的run方法,再继续执行下面的代码。
join() = join(0),主线程无限等待子线程执行完毕。
join(n milliseconds),主线程只等待n毫秒,n毫秒后无论子线程是否执行完毕,主线程都将继续执行下面的代码。
package com.jack.test; public class TestJoin implements Runnable{
public static int a = 0; public void run(){
try{
Thread.sleep(1100);
for(int i = 0; i < 5; i++){
a = a +1;
}
System.out.println("after for loop, a="+a);
}catch(InterruptedException e){
e.printStackTrace();
} } public static void main(String[] args) throws InterruptedException{
Runnable r = new TestJoin();
Thread t = new Thread(r);
t.start();
t.join();
System.out.println(a);
} }