(1)作用
实际上就是等待子线程执行完,主线程后面的代码才能执行(相当于wait)
(2)实例
1.未使用join
import java.util.concurrent.TimeUnit;
public class JoinTest {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sub thread "+Thread.currentThread().getName()+" end");
}
});
thread.start();
System.out.println("main thread end;");
}
}
结果为:(不一定一直是这样)main thread end;
sub thread Thread-0 end
也就是说:主线程执行结束了,子线程才结束 2.使用join
import java.util.concurrent.TimeUnit;
public class JoinTest {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sub thread "+Thread.currentThread().getName()+" end");
}
});
thread.start();
try {
thread.join();//等待线程执行完
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main thread end;");
}
}
结果一定为:
sub thread Thread-0 end
main thread end;