代码块
我们用实例进行讲解
//测试join方法
public class TestJion implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程vip来了"+i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动我们的线程
TestJion testJion = new TestJion();
Thread thread = new Thread(testJion);
thread.start();
for (int i = 0; i < 500; i++) {
if (i == 200){
thread.join();
}
System.out.println("main"+i);
}
}
}
运行结果:主线程运行到200之前两个线程谁抢到cpu谁执行
主线程执行到200之后,“插队”线程一直执行到结束,主线程才继续执行
总结
join方法就是让使用该方法的线程优先执行,在其执行结束之前其他线程等待执行
可以想象成插队