为了账号安全,请及时绑定邮箱和手机立即绑定

对main线程使用join方法,为什么main线程处于一直阻塞状态?

对main线程使用join方法,为什么main线程处于一直阻塞状态?

梦里花落0921 2019-03-19 17:18:45
public class JoinTest {public static void main(String[] args) throws InterruptedException {    MyThread3 thread=new MyThread3();    thread.start();    //thread.join(1);//将主线程加入到子线程后面,不过如果子线程在1毫秒时间内没执行完,则主线程便不再等待它执行完,进入就绪状态,等待cpu调度    System.out.println(Thread.currentThread());    Thread.currentThread().join();    for(int i=0;i<30;i++){        System.out.println(Thread.currentThread().getName() + "线程第" + i + "次执行!");    }}}class MyThread3 extends Thread {@Overridepublic void run() {        for (int i = 0; i < 1000; i++) {        try {            System.out.println(this.getName() + "线程第" + i + "次执行!");            Thread.sleep(1);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}}
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

那你得先知道join函数是干嘛用的啊!我们先来看看文档:


/**

 * Waits for this thread to die.

 *

 * <p> An invocation of this method behaves in exactly the same

 * way as the invocation

 *

 * <blockquote>

 * {@linkplain #join(long) join}{@code (0)}

 * </blockquote>

 *

 * @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.

 */

第一句话就说了Waits for this thread to die,你在主线程上执行"我要等到主线程结束,当前线程才能结束",这不成死循环了么。


查看完整回答
反对 回复 2019-04-19
  • 1 回答
  • 0 关注
  • 470 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号