bibek
bibek

Reputation: 151

need for a start method in java when using threads

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

Upvotes: 1

Views: 283

Answers (4)

Ammy
Ammy

Reputation: 379

in java Thread is always created in Stack Memory.When you create a new Thread it takes new memory in Stack.When you call start() method it initialize in new Stack Memory and when you call run() method it initialize in same Stack Memory That is why we always call a Thread with start() method

Upvotes: 0

Zak
Zak

Reputation: 7078

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500065

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.

Upvotes: 6

Joachim Sauer
Joachim Sauer

Reputation: 308001

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.

Upvotes: 3

Related Questions