簡體   English   中英

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

[英]Why does Java main method code execute, despite calling a Thread's run( ) method?

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++;
        }       
    }   
}

我注意到,在執行run out內Sys方法的同時,main方法內的Sys out同時運行。

The output looks as follows:
Sleeping for 500 seconds within run method
Sleeping for 500 seconds within run method
 Within main method
Sleeping for 500 seconds within run method
 Within main method
 Within main method
Sleeping for 500 seconds within run method
Sleeping for 500 seconds within run method
 Within main method
 Within main method
 Within main method

當我們調用thr.start()時,不應在run()處完成執行,然后返回到while(instance.count!= 5)行。

您的run方法不會從主線程中調用。 相反, start創建一個新的執行線程(獨立於主線程),然后該新線程執行run 主線程將立即(無需等待新線程發生什么情況)在start之后恢復下一條指令。

正是這種並發性正是您要使用Thread

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM