加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

一道关于Thread的题

发布时间:2020-12-15 00:43:03 所属栏目:C语言 来源:网络整理
导读:早上无事看到这个: public static void main(String[] args)throws InterruptedException{Thread t = new Thread(new MyThread2()); t.start(); System.out.print("main1"); t.join(); System.out.print("main2");}@Overridepublic void run() { System.out

早上无事看到这个:

public static void main(String[] args)throws InterruptedException{
Thread t = new Thread(new MyThread2());
    t.start();
    System.out.print("main1");
    t.join();
    System.out.print("main2");
}

@Override
public void run() {
    System.out.print("run1");
    System.out.print("run2");
}

}

  • 因为join(),main2肯定最后打印;

  • run1 run2 打印顺序固定为:run1,run2;

  • 主要有点疑惑,main1,和run里面的到底谁先打印?

    run() method of
        * the receiver will be called by the receiver Thread itself (and not the
        * Thread calling start()).
        *
        * @throws IllegalThreadStateException - if this thread has already started.
        * @see Thread#run
        */
       public synchronized void start() {
           checkNotStarted();
    
       hasBeenStarted = true;
    
       nativeCreate(this,stackSize,daemon);

    }

看到start里的native开头,我就GG了。但是我知道,Thread的start不会阻塞主线程的运行,所以main1打印最先。

然后,敲代码多次运行验证:

G:java>javac MyThread2.java

G:java>java MyThread2
main1run1run2main2

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读