Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

java - Please explain the output from Thread run() and start() methods

Please explain the output of the below code:

If I call th1.run(), the output is:

EXTENDS RUN>>
RUNNABLE RUN>>

If I call th1.start(), the output is:

RUNNABLE RUN>>
EXTENDS RUN>>

Why this inconsistency? Please explain.

class ThreadExample extends Thread{
    public void run() {
        System.out.println("EXTENDS RUN>>");
    }
}

class ThreadExampleRunnable implements Runnable {
    public void run() {
        System.out.println("RUNNABLE RUN>>");
    }
}

class ThreadExampleMain{
    public static void main(String[] args) {
        ThreadExample th1 = new ThreadExample();
        //th1.start(); 
        th1.run();

        ThreadExampleRunnable th2 = new ThreadExampleRunnable();
        th2.run();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Thread.start() method starts a new thread, the entry point for this thread is the run() method. If you call run() directly it will execute in the same thread. Given that calling Thread.start() will start a new thread of execution, the run() method may be called after (as in you example) the rest of the main method executes.

Change your main method to call th1.start() and run repeatedly, you will see that sometimes it outputs:

EXTENDS RUN>>
RUNNABLE RUN >>

and sometimes it outputs:

RUNNABLE RUN >>
EXTENDS RUN>>

depending on how java chooses to schedule your 2 threads.

Check out the java tutorial on this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...