在Java语言中,join()方法的作用是让调用该方法的线程在执行完run()方法后,再执行join方法后面的代码。简单的说,就是将两个线程合并,用于实现同步功能。具体而言,可以通过线程A的join()方法来等待线程A的结束,或者使用线程A的join(2000)方法来等待线程A的结束,但最多只等待2s。
我的理解:
threadA.join()相当于threadA插队运行。试想这样的场景:有A、B两个线程,A线程在运行,如果A想让B运行,只需要执行Thread.sleep(time)就可以让B运行了。如果有第三个线程C呢?A让出CPU,B和C争抢运行权但不一定是B抢到。所以在A中执行B.join()就可以让B插个队执行了。如果B.join(t),就是让B插队执行t时间,时间一到不管B的run()方法有没有执行完都要把运行权还给A。
示例如下:
//线程类
class MyThread implements Runnable{
public void run(){
try {
System.out.println("线程开始...");
Thread.sleep(5000);
System.out.println("线程结束");
} catch (Exception e) {
//TODO: handle exception
}
}
}
public class Test{
public static void main(String[] args){
Thread t = new Thread(new MyThread());
t.start();
try {
//主线程等待t线程结束,只等1秒
t.join(1000);
if(t.isAlive())
System.out.println("t线程没有结束");
else
System.out.println("t线程结束");
} catch (Exception e) {
//TODO: handle exception
}
}
}