Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It may be a basic question, i was confused with this,

in one file i have like this :

public class MyThread extends Thread {
    @Override
    public void run() {
        //stuffs
    }
}

now in another file i have this :

public class Test {
    public static void main(String[] args) {
        Thread obj = new MyThread();

        //now cases where i got confused
        //case 1
        obj.start();   //it makes the run() method run
        //case 2
        obj.run();     //it is also making run() method run
    }
}

so in above what is the difference between two cases, is it case 1 is creating a new thread and case 2 is not creating a thread ? that's my guess...hope for better answer SO guys.Thanks

See Question&Answers more detail:os

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

1 Answer

start() runs the code in run() in a new thread. Calling run() directly does not execute run() in a new thread, but rather the thread run() was called from.

If you call run() directly, you're not threading. Calling run() directly will block until whatever code in run() completes. start() creates a new thread, and since the code in run is running in that new thread, start() returns immediately. (Well, technically not immediately, but rather after it's done creating the new thread and kicking it off.)

Also, you should be implementing runnable, not extending thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...