views:

95

answers:

3

Why do we need to run the thread through start method and not directly through the run method ?

+3  A: 

Because the run method contains the code that the new thread should execute.

If you were to call the run method, then you'd just execute it on the current thread.

Calling start starts the new thread and then executes the run method on the new thread.

Joachim Sauer
Out of curiosity: How is this wrong? Why the downvote?
Joachim Sauer
+6  A: 

The run method just executes the thread's task in the current thread. Historically, you would subclass Thread and override run - although today the preferred mechanism is to pass the Thread constructor a Runnable. So run itself doesn't do any threading - it's start which creates a new "actual" thread (as opposed to just a Thread object) and makes it execute run() when it's started.

Jon Skeet
+1  A: 

The start() method tells the JVM that it needs to create a system specific thread. After creating the system resource, it passes the Runnable object to it to execute its run() method. Calling the run() method directly has the "Thread" execute in the same thread as the calling object, not in a separate thread of execution, as intended.

In other words, calling run() is just like a normal method call. Whereas, calling start() tells the thread to create the necessary system resources and then execute the run() method asynchronously.

EDIT:

For example,

Pseudo code1:

thread one = new thread();
thread two = new thread();
one.run();
two.run();

This makes the threads run sequentially,ie, two.run(); will run only after one.run(); finishes.


Pseudo code2:

thread one = new thread();
thread two = new thread();
one.start();
two.start();

In this case both threads start and run simultaneously.

The start() method calls the run() method asynchronously (doesnt waits for any result, just fires up an action), but when WE call run(), it runs synchronously, ie,it waits until run() finishes and only then it proceeds to the next line of code.

Zaki