Join:等待该线程执行完再继续(Waits for this thread to die)
public class TestJoin {
public static void main(String[] args) {
CustomThread t1 = new CustomThread("t1");
CustomThread t2 = new CustomThread("t2");
CustomThread t3 = new CustomThread("t3");
t1.start();
try {
t1.join(); // main thread等待t1执行完在继续执行
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("go on....");
t2.start();
t3.start();
}
}
class CustomThread extends Thread {
public CustomThread(String name){
super(name);
}
public void run(){
for(int i=0;i < 5;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行:" + (i+1));
}
}
}
输出结果如下:
t1执行:1
t1执行:2
t1执行:3
t1执行:4
t1执行:5
go on....
t3执行:1
t2执行:1
t3执行:2
t2执行:2
t3执行:3
t2执行:3
t3执行:4
t2执行:4
t3执行:5
t2执行:5
本文通过一个具体的Java示例程序介绍了线程中Join方法的使用方式及其作用。该示例展示了如何使主线程等待子线程执行完毕后再继续执行,并通过输出结果验证了Join方法的效果。
780

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



