[java] java 线程join方法详解

join方法的做用是使所属线程对象正常执行run方法,而对当前线程无限期阻塞,直到所属线程销毁后再执行当前线程的逻辑。

1、先看普通的无join方法
NoJoin.java

复制代码

public class NoJoin  extends  Thread{
    @Override    public void run() {        try {            long count = (long)(Math.random()*100);
            System.out.println(count);
            Thread.sleep(count);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

复制代码

复制代码

public class NoJoinTest {    public static  void main(String[] args){

        NoJoin noJoin = new NoJoin();
        noJoin.start();
        System.out.println("执行到main....");
    }
}

复制代码

输出:java

如今要先输出时间,再执行main方法。app

只须要添加join方法便可。dom

复制代码

/**
 * Created by Administrator on 2016/1/5 0005.
 *
 * join方法的做用是使所属线程对象正常执行run方法,而对当前线程无限期阻塞,直到所属线程销毁后再执行当前线程的逻辑。 */public class JoinTest {    public static  void main(String[] args){        try {
            NoJoin noJoin = new NoJoin();
            noJoin.start();
            noJoin.join();//join
            System.out.println("执行到main....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

复制代码

 

查看join源代码:ide

复制代码

 /**
     * 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) {            while (isAlive()) {
                wait(0);
            }
        } else {            while (isAlive()) {                long delay = millis - now;                if (delay <= 0) {                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

复制代码

可见,join内部是对象的wait方法,当执行wait(mils)方法时,必定时间会自动释放对象锁。oop

相关文章
相关标签/搜索