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
run() method after calling start() : this is executed by your thread which is created by you, it is allocated processor to run independently.
run() method called by you : executed from your calling thread.
start() starts the thread. run() just runs the code, in the current thread.
the simple answer to your question is this:
run(): runs the code in the run() method, blocking until it's complete
start(): returns immediately (without blocking) and another thread runs the code in the run() method
Calling start() will create a new execution thread, and then the run() will be executed in the newly created thread
where as directly calling run() will execute the code in the current thread
In one line directly calling run()
is synchronous (your code will block until run() returns) and calling start()
(your code will not wait for run to complete as it is called in other thread obj
) is asynchronous.
When you directly use start()
method, then the thread will run once using the Runnable instance you provided to it and then the thread will be unusable.
But to leverage the Thread Pooling and Scheduling capabilities that are inbuilt in Java, extending a Runnable or Callable is the way to go.
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.