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