1. 程式人生 > >JAVA多執行緒之(join)

JAVA多執行緒之(join)

 /**
     * Waits at most <code>millis</code> milliseconds for this thread to 
     * die. A timeout of <code>0</code> means to wait forever. 
     *
     * @param      millis   the time to wait in milliseconds.
     * @exception  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;
	    }
	}
    }
Thread join 方法例項程式碼如下:
package nc.com.thread.traditional.example;
/**
* @ClassName: ThreadJoin 
* @Description: TODO(這裡用一句話描述這個類的作用) 
* @author A18ccms a18ccms_gmail_com 
* @date 2015-12-19 下午06:35:15 
*
 */
public class ThreadJoin {
	 private Object object = new Object();
	 private int i = 10;
	public static void main(String[] args) {
		/**
		 * 有join時輸出:
		 */
		ThreadJoin j = new ThreadJoin();
		DemoThread t1 = j.new DemoThread();
		t1.start();
		try {
			//執行join方法後,主執行緒進入阻塞狀態,直到子執行緒執行結束
			t1.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("----------主執行緒已經等到了子執行緒執行結束,繼續執行主執行緒--------");
	}
	 class DemoThread extends Thread{
	    @Override
	    public void run() {
	        synchronized (object) {
	            i++;
	            System.out.println("i:"+i);
	            try {
	                System.out.println("執行緒"+Thread.currentThread().getName()+"進入睡眠狀態");
	            } catch (Exception e) {
	                // TODO: handle exception
	            }
	            System.out.println("執行緒"+Thread.currentThread().getName()+"睡眠結束");
	            i++;
	            System.out.println("i:"+i);
	        }
	    }
	}
}

輸出:

   i:11
執行緒Thread-0進入睡眠狀態
執行緒Thread-0睡眠結束
i:12
----------主執行緒已經等到了子執行緒執行結束,繼續執行主執行緒--------