join方法的作用是使所属线程对象正常执行run方法,而对当前线程无限期阻塞,直到所属线程销毁后再执行当前线程的逻辑。
一、先看普通的无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...."); } }
输出:
现在要先输出时间,再执行main方法。
只需要添加join方法即可。
/** * 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源代码:
/** * 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)方法时,一定时间会自动释放对象锁。