簡體   English   中英

Java線程執行順序

[英]Java thread order of execution

我有這個java主要方法

public class ThreadJoinExample {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        TestJoinClass t1 = new TestJoinClass("t1");  
        TestJoinClass t2 = new TestJoinClass("t2");  
        TestJoinClass t3 = new TestJoinClass("t3");  
        t1.start();  
        try{  
            t1.join();  
        }catch(Exception e){System.out.println(e);}  
        t2.start(); 
        //thread 3 won't start until thread 2 is complete
        t3.start();  
    }

}

我的線程類是

public class TestJoinClass extends Thread{
    //Constructor to assign a user defined name to the thread
    public TestJoinClass(String name)
    {
        super(name);
    }
    public void run(){  
        for(int i=1;i<=5;i++){  
        try{
            //stop the thread for 1/2 second
            Thread.sleep(500);  
            }
        catch(Exception e){System.out.println(e);}  
        System.out.println(Thread.currentThread().getName()+
                " i = "+i);  
        }  
     }
}

該程序的輸出是

t1 i = 1
t1 i = 2
t1 i = 3
t1 i = 4
t1 i = 5
t3 i = 1
t2 i = 1
t3 i = 2
t2 i = 2
t3 i = 3
t2 i = 3
t3 i = 4
t2 i = 4
t3 i = 5
t2 i = 5

我只是一個小問題。 我想知道為什么t3開始而不是t2開始運行? 在代碼中,它表明t2.start()在t3.start()之前先執行。 輸出是否不應該表明t2在t3之前也首先執行? 謝謝

這表明了許多人對Java並發性的理解中的一個常見錯誤。

您的bug在這里:

//thread 3 won't start until thread 2 is complete

它應該讀

//thread 2 and 3 will run in parallel, may start in any order and may also interleave their output

當Java線程的對象調用其start()方法時,程序准備在單獨的線程中執行run()方法,並且原始調用線程繼續執行。 因此,只要t2.start(); 被調用時, t2線程准備執行其run方法的代碼。

但它不能保證在T2的run()的第一行代碼會在代碼執行()的T3的run()雖然t2.start的第一行代碼()t3.start之前被調用之前首先執行。 因此,對於不同的機器/不同的運行等,當前代碼的t2和t3可能會獲得不同的執行順序和輸出。

因此,總結是,由VM完全決定首先執行並行執行的run()方法中的兩個方法之間的哪一行代碼。

暫無
暫無

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

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