亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

盡管調用了 Thread 的 run() 方法,為什么 Java 的 main 方法代碼仍然執行?

盡管調用了 Thread 的 run() 方法,為什么 Java 的 main 方法代碼仍然執行?

回首憶惘然 2022-11-10 16:25:08
public class RunnableThreadExample implements Runnable {    public int count = 0;    public static void main(String[] args) {        RunnableThreadExample instance = new RunnableThreadExample();        Thread thr = new Thread(instance);        thr.start();                while(instance.count != 5) {                        try {                Thread.sleep(500);                System.out.println(" Within main method");            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }                   }           }    @Override    public void run() {        while(count < 5) {            try {                System.out.println("Sleeping for 500 seconds within run method");                Thread.sleep(500);                          } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }                       count++;        }           }   }我注意到 Sys out within main 方法同時運行,而 Sys out within run ( ) 方法被執行。The output looks as follows:Sleeping for 500 seconds within run methodSleeping for 500 seconds within run method Within main methodSleeping for 500 seconds within run method Within main method Within main methodSleeping for 500 seconds within run methodSleeping for 500 seconds within run method Within main method Within main method Within main method當我們調用 thr.start() 時,不應該在 run() 處完成執行,然后回到 while(instance.count != 5) { ??
查看完整描述

1 回答

?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

不會從主線程調用您的run方法。相反,創建一個新的執行線程(獨立于主線程),并且該新線程執行. 主線程將立即(無需等待新線程發生什么)恢復 . 之后的下一條指令。startrunstart

這種并發正是您要使用Thread.


查看完整回答
反對 回復 2022-11-10
  • 1 回答
  • 0 關注
  • 87 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號