深入理解join()方法
程序员文章站
2022-06-10 23:42:01
...
全文概要
本文主要介绍Thread中join()方法的使用场景。
join()方法介绍
- 代码案例
package com.tml.javaCore.thread;
/**
* <p>Thread类中join()方法
* @author Administrator
*
*/
public class JoinDemo {
public static void main(String[] args) {
JoinDemo demo = new JoinDemo();
Thread thread_01 = new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + "ready!");
Thread thread_02 =new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + "ready!");
demo.print();
System.out.println(Thread.currentThread().getName() + " end!");
}
}, "thread_02");
thread_02.start();
try {
thread_02.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
demo.print();
System.out.println(Thread.currentThread().getName() + " end!");
}
}, "thread_01");
thread_01.start();
}
private void print(){
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +" :is printing :" + i);
}
}
}
- 输出结果
thread_02ready!
thread_02 :is printing :0
thread_02 :is printing :1
thread_02 :is printing :2
thread_02 :is printing :3
thread_02 :is printing :4
thread_02 :is printing :5
thread_02 :is printing :6
thread_02 :is printing :7
thread_02 :is printing :8
thread_02 :is printing :9
thread_02 end!
thread_01 :is printing :0
thread_01 :is printing :1
thread_01 :is printing :2
thread_01 :is printing :3
thread_01 :is printing :4
thread_01 :is printing :5
thread_01 :is printing :6
thread_01 :is printing :7
thread_01 :is printing :8
thread_01 :is printing :9
thread_01 end!
- 结果分析
- 在main主线程中启动一个线程thread_01,而线程1中又新建了一个线程thread_02,执行thread_02.start()时启动了线程2;
- 当执行到thread_02.join()时,会让线程1进入阻塞等待状态,直到线程2全部执行完毕后,线程1才能执行;
- join()方法的使用场景也就不言而喻了,即主线程等待子线程全部执行完毕后,才继续执行主线程后续的逻辑。
上一篇: 关于CSS中浮动引发的特殊情况,“大坑”
下一篇: 我一把年纪了