What's the difference between Thread start() and Runnable run()
First example: No multiple threads. Both execute in single (existing) thread. No thread creation.
R1 r1 = new R1();
R2 r2 = new R2();
r1
and r2
are just two different objects of classes that implement the Runnable
interface and thus implement the run()
method. When you call r1.run()
you are executing it in the current thread.
Second example: Two separate threads.
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1
and t2
are objects of the class Thread
. When you call t1.start()
, it starts a new thread and calls the run()
method of r1
internally to execute it within that new thread.
What is the difference between Thread.start() and Thread.run()?
No, you can't. Calling run will execute run()
method in the same thread, without starting new thread.
Java multithreading difference between run() and start()
It's amazing how many people can answer a question by repeating what the OP already wrote without actually answering the question.
The solution is that you are first asking for the name of the running thread, but the second time you ask for the name of the thread insurance where the code or executed. If you change the later to Thread.currentThread
instead of this
you will get the expected answer.
Difference between running and starting a thread
Thread.run()
does not spawn a new thread whereas Thread.start()
does, i.e Thread.run
actually runs on the same thread as that of the caller whereas Thread.start()
creates a new thread on which the task is run.
What will happen use run() instead of start() of a thread?
Calling run
directly on a Thread
object defeats the point of having the Thread
in the first place.
If you call run
, then run
will execute in the current Thread
, as a normal method. You must call the start
method on the Thread
to have run
execute in a different Thread
.
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
When would you call java's thread.run() instead of thread.start()?
You might want to call run() in a particular unit test that is concerned strictly with functionality and not with concurrency.
Related Topics
Integer Wrapper Objects Share the Same Instances Only Within the Value 127
How to Set a Background Picture in JPAnel
Use Mockito to Mock Some Methods But Not Others
Why Jsf Saves the State of UI Components on Server
When Should a Class Be Comparable And/Or Comparator
Best Way to List Files in Java, Sorted by Date Modified
Why Can't Strings Be Mutable in Java and .Net
Difference Between String Replace() and Replaceall()
In What Order Do Static/Instance Initializer Blocks in Java Run
How to Reload Properties With Spring
How to Initialise a Static Map
Java Class That Implements Map and Keeps Insertion Order