JAVA多线程之(join)

 java多线程中,join方法是主线程等待一个子线程结束后再继续执行主线程后续代码,wait方法会让线程进入阻塞状态,并且会释放线程占有的锁,并交出CPU执行权限,由于wait方法会让线程释放对象锁,研究java Thread类的join方法发现,其实join方法也是调用wait方法实现,所以join方法同样会让线程释放对一个对象持有的锁

Thread类的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
----------主线程已经等到了子线程执行结束,继续执行主线程--------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值