Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Thread start() and Runnable run()

People also ask

What is 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 is the difference between run () and start () methods in thread Mcq?

Explanation: run() method is used to define the code that constitutes the new thread, it contains the code to be executed. start() method is used to begin execution of the thread that is execution of run().

What is the difference between runnable and thread?

Runnable is an interface which represents a task that could be executed by either a Thread or Executor or some similar means. On the other hand, Thread is a class which creates a new thread. Implementing the Runnable interface doesn't create a new thread.


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.


If you just invoke run() directly, it's executed on the calling thread, just like any other method call. Thread.start() is required to actually create a new thread so that the runnable's run method is executed in parallel.


The difference is that Thread.start() starts a thread that calls the run() method, while Runnable.run() just calls the run() method on the current thread.


The difference is that when program calls start() method, a new thread is created and code inside run() is executed in the new thread: while if you call run() method directly, no new thread will be created and code inside run() will execute in the current thread directly.

Another difference between start() and run() in Java thread is that you cannot call start() twice. Once started, second start() call will throw IllegalStateException in Java while you can call run() method several times since it's just an ordinary method.