join 方法
join 方法能够使得当先线程抢占主线程的执行,等待当前线程执行完,再执行主线程。join 方法也可添加参数,表示抢占多少毫秒。
我们编写了一个 Join 类,用来输出数字0-9
public class Join implements Runnable{
@Override
public void run() {
for (int i=0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"正在运行"+"第"+i+"次for循环.");
}
}
}
我们编写一个测试类 JoinThreadDemo, 里面有两个线程, 分别是主线程 和 jt1 线程。启动 jt1 线程以后, 设置该线程为join模式,观察运行结果。
public class JoinThreadDemo {
public static void main(String[] args) throws InterruptedException {
Join jt1= new Join();
Thread t1=new Thread(jt1,"jt1");
t1.start();
//在主线程中 调用 t1 线程, t1 线程使用join方法, 主线程被阻塞
t1.join();
for (int i = 0; i < 10; i++) {
System.out.println("main thread 正在运行"+"第"+i+"次for循环.");
}
}
}
运行结果:
t1正在运行第0次for循环.
t1正在运行第1次for循环.
t1正在运行第2次for循环.
t1正在运行第3次for循环.
t1正在运行第4次for循环.
t1正在运行第5次for循环.
t1正在运行第6次for循环.
t1正在运行第7次for循环.
t1正在运行第8次for循环.
t1正在运行第9次for循环.
main thread 正在运行第0次for循环.
main thread 正在运行第1次for循环.
main thread 正在运行第2次for循环.
main thread 正在运行第3次for循环.
main thread 正在运行第4次for循环.
main thread 正在运行第5次for循环.
main thread 正在运行第6次for循环.
main thread 正在运行第7次for循环.
main thread 正在运行第8次for循环.
main thread 正在运行第9次for循环.
运行结果显示,无论重复多少次,始终是 t1 先执行完毕, 再执行主线程。
Last updated