和wait()有点类似,join()方法可以让多个线程之间排队等待,按照一定的顺序执行。join方法是阻塞的,会一直等到取消或超时为止。假如现在有三个线程,main,t0,t1,要在main线程启动之后相继执行t0,t1,那么可以在main线程之后,启动t0,t0加入执行队列,即t0.join(),之后再启动t1,t1.join()。
public class JoinDemo {
public static void main(String args[]) throws InterruptedException{
System.out.println(Thread.currentThread().getName() + " is Started");
Thread t0 = new Thread(){
public void run(){
try {
System.out.println(Thread.currentThread().getName() + " is Started,sleep 2 second");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " is Completed");
} catch (InterruptedException ex) {
}
}
};
t0.start();
t0.join();
Thread t1 = new Thread(){
public void run(){
try {
System.out.println(Thread.currentThread().getName() + " is Started,sleep 6 second");
Thread.sleep(6000);
System.out.println(Thread.currentThread().getName() + " is Completed");
} catch (InterruptedException ex) {
}
}
};
t1.start();
t1.join();
System.out.println(Thread.currentThread().getName() + " is Completed");
}
}
执行结果:
main is Started
Thread-0 is Started,sleep 2 second
Thread-0 is Completed
Thread-1 is Started,sleep 6 second
Thread-1 is Completed
main is Completed
本文通过一个具体的Java示例程序介绍了线程中join方法的使用方式及其作用。该方法可以使主线程等待子线程执行完毕后再继续执行,确保了线程间的有序执行。
1728

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



