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

Categories

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

java - Running Thread by calling start() and run(), what is the difference?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...