【Android笔记】Thread类中关于join()方法的源码分析

1、join()方法的作用

例如有一个线程对象为Thread1,在main()方法中调用Thread1.join()方法可使得当前线程(即主线程)阻塞,而执行Thread1线程。

2、源码分析(以上面的例子为例)

/**
 * 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 (当
millis 为负数时抛出此异常)
 *          if the value of {@code millis} is negative
*
* @throws InterruptedException (如果有任何线程中断了当前线程(当前线程为main线程),抛出此异常,当前线程的中断状态将被清除。该异常由源码中的wait()抛出
)
 *          if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
//这段代码是由main线程执行的
public final void join(long millis) throws InterruptedException { synchronized(lock) { //这里的lock是在Thread1中创建的,源码为 private final Object lock=new Object();
//main线程获取对象lock的锁
long base = System.currentTimeMillis();//获取系统当前时间毫秒值 long now = 0; //表示等待了多少时间 if (millis < 0) { //抛出 millis 为负数的异常 throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { //毫秒值为零,意味着等待到Thread1结束 while (isAlive()) { //当Thread1线程还活着时 lock.wait(0); //使得拥有lock对象的锁的线程(main线程)停止,并使得当前线程释放锁,那什么时候调用notifyAll呢?这个答案在 jvm源码中,在此不细述 } //中断异常也是由wait()方法抛出 } else { //否则,等待millis while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; // 等待时间结束,跳出了join()方法,main线程继续执行 } lock.wait(delay); //延时等待 now = System.currentTimeMillis() - base; //更新now } } } }

 

转载于:https://www.cnblogs.com/Blue-Keroro/p/9032609.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值