Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we call Thread.start() method which in turns calls run method?

Why do we call the thread object's start() method which in turns calls run() method, why not we directly call run() method?

like image 265
Anu Avatar asked Nov 08 '11 15:11

Anu


People also ask

What is the difference between calling start () and run () method of thread?

start method of thread class is implemented as when it is called a new Thread is created and code inside run() method is executed in that new Thread. While if run method is executed directly than no new Thread is created and code inside run() will execute on current Thread and no multi-threading will take place.

What will happen if we call the run () method instead of calling the start () method when starting a thread?

The run method is just another method. If you call it directly, then it will execute not in another thread, but in the current thread. If start isn't called, then the Thread created will never run. The main thread will finish and the Thread will be garbage collected.

Which method start a thread by calling the run method?

Java Thread start() method The start() method internally calls the run() method of Runnable interface to execute the code specified in the run() method in a separate thread. The thread moves from New State to Runnable state. When the thread gets a chance to execute, its target run() method will run.

What happens when you call the Start () method on a thread object?

New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed.


2 Answers

[...] why not we directly call run() method?

The run() method is just an ordinary method (overridden by you). As with any other ordinary method and calling it directly will cause the current thread to execute run().

All magic happens inside start(). The start() method will cause the JVM to spawn a new thread and make the newly spawned thread execute run().

like image 65
aioobe Avatar answered Sep 21 '22 01:09

aioobe


If you directly call run() method its body is executed in context of current thread. When you invoke start() method a new thread is created and run() method is executed in this new thread.

like image 32
AlexR Avatar answered Sep 22 '22 01:09

AlexR