java基础知识回顾之java Thread类学习(十一)--join方法的理解



以下面例子说明下面的源码:main 线程 和 A线程,A线程是main线程创建并且启动的,main线程优先级比较高,正在执行;
这个时候main线程调用A.join()之后,main线程一直等待,直到A线程运行完毕,main线程才运行。

join方法的源码:      

* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever. * * <p> This implementation uses a loop of {@code this.wait} calls * conditioned on {@code this.isAlive}. As a thread terminates the * {@code this.notifyAll} method is invoked. It is recommended that * applications not use {@code wait}, {@code notify}, or * {@code notifyAll} on {@code Thread} instances. * * @param millis * the time to wait in milliseconds * * @throws IllegalArgumentException * if the value of {@code millis} is negative * * @throws InterruptedException * if any thread has interrupted the current thread. The * <i>interrupted status</i> of the current thread is * cleared when this exception is thrown.
*/
// 加锁当前线程
public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) {
//A线程是start,在运行中 while (isAlive()) {
          //main线程等待 wait(0); } } else {
//join(timeOut)的情况 while (isAlive()) {
          //根据当前timeout的时间-now 是否<=0进行判断,主线程是否继续阻塞等待 long delay = millis - now;
//等待超时时间到了,则主线程不阻塞了,等待结束 if (delay <= 0) { break; } wait(delay);
//子线程从循环开始到现在运行的时间 now = System.currentTimeMillis() - base; } } }

给一个例子来理解:

package concurrentMy.joins;

/**
 * 
 * @author Administrator
 * 
 * main 线程 和 A线程,A线程是main线程创建并且启动的,main线程优先级比较高,正在执行;
 * 这个时候main线程调用A.join()之后,main线程一直等待,直到A线程运行完毕,main线程才运行
 * 
 */
class ThreadA extends Thread {
    
    public ThreadA(String name){
        super(name);
    }

    @Override
    public void run() {
       
        for (int i = 0; i < 20; i++) { // 复写父类的toString方法, 返回该线程的字符串表示形式,包括线程名称、优先级和线程组。 System.out.println(Thread.currentThread().getName() + "-" + i); } } } public class JoinDemo {  /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { ThreadA A = new ThreadA("线程A"); A.start(); A.join(); //A线程加入到“main线程”中,main线程一直等待,直到A线程执行完毕,main线程才运行 System.out.println(Thread.currentThread().getName() + "执行"); System.out.println(Thread.currentThread().getName() + "执行终止"); } }

 输出结果:

线程A-0
线程A-1
线程A-2
线程A-3
线程A-4
线程A-5 线程A-6 线程A-7 线程A-8 线程A-9 线程A-10 线程A-11 线程A-12 线程A-13 线程A-14 线程A-15 线程A-16 线程A-17 线程A-18 线程A-19 main执行 main执行终止  

代码运行整个过程说明入下图:

 

 

 

转载于:https://www.cnblogs.com/200911/p/6027358.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值