(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;
本文详细介绍了Java中线程等待与join方法的作用及使用示例,通过对比未使用join方法与使用join方法的不同结果,阐述了join方法在控制线程执行顺序中的重要性。
2007

被折叠的 条评论
为什么被折叠?



