Java---join()方法的作用

来源:互联网 发布:服务器网卡聚合linux 编辑:程序博客网 时间:2024/06/05 03:23

书中的解释是:join()方法就是指调用该方法的线程在执行完run()方法后,再执行join方法后面的代码,即将两个线程合并,用于实现同步控制。

具体作用:

等待该线程终止,例如,在子线程调用了join(time)方法后,主线程只有等待子线程time时间后才能执行子线程后面的代码。

具体代码:

public class joinTest {class ThreadImp implements Runnable {public void run(){try{System.out.println("Begin");Thread.sleep(1000);System.out.println("end");}catch(InterruptedException e) {e.printStackTrace();}}}//主线程public static void main(String[] args) {joinTest ts = new joinTest();//子线程Thread t = new Thread(ts.new ThreadImp());t.start();try{t.join(2000);if (t.isAlive()) {System.out.println("alive");} else {System.out.println("dead");}System.out.println("finished");} catch (InterruptedException e) {e.printStackTrace();}}}

运行结果为:

当将t.join(2000)改为t.join(1000)或者时间间隔更小时,运行结果如下:

从上述结果可以看出,如果子线程运行的时间超过join里面设置的时间,那么程序是先执行子线程,当超过join里面设置的时间时,主线程执行join后面的代码结束后,再执行子线程中剩余代码;

当子线程运行的时间小于join设置的时间,那么等到子线程的run方法结束后再执行join后面的代码。


原创粉丝点击