简体   繁体   中英

Java thread order of execution

I have this java main method as

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();  
    }

}

My thread class is

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

The output for this program is

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

I have just a minor question. I was wondering why does t3 start running first instead of t2? In the code, it shows that t2.start() executes first before t3.start(). Shouldn't the output show that t2 executes first before t3 as well? Thank you

This demonstrates a common bug in many peoples understanding of concurrency in Java.

Your bug is here:

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

it should read

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

When a java thread's object calls its start() method the program gets prepared to execute the run() method in a separate thread and the original calling thread continues to execute. So, as soon as t2.start(); is called, t2 thread prepares to execute codes of its run method.

But it is not guaranteed that first line of code in t2 's run() will be executed first before executing first line of code of t3's run() although t2.start() is called before t3.start() in code. So you may get different execution order & output for t2 & t3 for the current code on different machine / different run etc.

So, summary is it's totally up to the VM to choose which line of code between two of the parallel executing run() method gets executed first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM