簡體   English   中英

在執行下一行之前,main方法是否等待所有線程完成?

[英]does the main method wait until all the threads are done before executing the next line?

在Java中,如果我有一個從構造函數創建線程的類(通過調用該類的某些函數),我在main方法中創建該類的對象。 主方法是等待所有線程完成還是繼續到下一行?

例如:

public static void main(String[] args)  {
    WorksWithThreads obj = new WorksWithThreads ( );

    //does something else - does this line happen after all the 9 threads finished their job? 
}

class WorksWithThreads(){
    public WorksWithThreads(){
        for(int i=0;i<9;i++)
            WithThread tread= new WithThread();
    }

    private static class WithThread extends Thread {

        public WithThread () {
            run();
        }

        public void run(){
            //does something
        }
    }

}

我希望我不會太混亂..提前謝謝你.. Shiran

如果你實際上產生了新的Threads,那么main方法會在完成產生后立即繼續(但是在線程結束之前,假設它們運行一段時間)

但是你沒有產生線程。 您正在創建Thread類的實例。 要實際生成新線程,您必須調用start。 像你一樣調用run()只是一個普通的方法調用,處理只有在完成后才會繼續。

您可能希望完成有關此主題官方教程

不。線程的關鍵在於它們不會停止生成它們的線程的執行。 一旦WorksWithThreads完成所有線程的生成, main()將繼續執行,但它生成的線程將與main的其余部分同時執行。

是的,它將在創建9個線程后運行。你甚至沒有啟動那9個線程。所以在它們執行之前,下一行將在main中執行

暫無
暫無

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

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