Reputation: 18489
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
Upvotes: 2
Views: 955
Reputation: 310907
start() starts the thread. run() just runs the code, in the current thread.
Upvotes: 1
Reputation: 41945
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.
Upvotes: 1
Reputation: 33447
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.
Upvotes: 18
Reputation: 16158
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.
Upvotes: 2
Reputation: 1074335
Calling start
starts the thread. It does the underlying work to create and launch the new thread, and then calls run
on that new thread.
Calling run
just calls the run
method, on the current thread. You never call run
directly, use start
.
Upvotes: 2
Reputation: 4006
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
Upvotes: 2
Reputation: 13465
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
Upvotes: 2