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

Say we have these two Runnables:

class R1 implements Runnable {
    public void run() { … }
    …
}

class R2 implements Runnable {
    public void run() { … }
    …
}

Then what's the difference between this:

public static void main() {
    R1 r1 = new R1();
    R2 r2 = new R2();

    r1.run();
    r2.run();
}

And this:

public static void main() {
    R1 r1 = new R1();
    R2 r2 = new R2();
    Thread t1 = new Thread(r1);
    Thread t2 = new Thread(r2);

    t1.start();
    t2.start();
}

This question is related to java multithreading concurrency runnable

The answer is


The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.


invoke run() is executing on the calling thread, like any other method call. whereas Thread.start() creates a new thread. invoking run() is a programmatic bug.


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.


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.


If you do run() in main method, the thread of main method will invoke the run method instead of the thread you require to run.

The start() method creates new thread and for which the run() method has to be done


t.start() is the method that the library provides for your code to call when you want a new thread.

r.run() is the method that you provide for the library to call in the new thread.


Most of these answers miss the big picture, which is that, as far as the Java language is concerned, there is no more difference between t.start() and r.run() than there is between any other two methods.

They're both just methods. They both run in the thread that called them. They both do whatever they were coded to do, and then they both return, still in the same thread, to their callers.

The biggest difference is that most of the code for t.start() is native code while, in most cases, the code for r.run() is going to be pure Java. But that's not much of a difference. Code is code. Native code is harder to find, and harder to understand when you find it, but it's still just code that tells the computer what to do.

So, what does t.start() do?

It creates a new native thread, it arranges for that thread to call t.run(), and then it tells the OS to let the new thread run. Then it returns.

And what does r.run() do?

The funny thing is, the person asking this question is the person who wrote it. r.run() does whatever you (i.e., the developer who wrote it) designed it to do.


Start() method call run override method of Thread extended class and Runnable implements interface.

But by calling run() it search for run method but if class implementing Runnable interface then it call run() override method of Runnable.

ex.:

`

public class Main1
{
A a=new A();
B b=new B();
a.run();//This call run() of Thread because run() of Thread only call when class 
        //implements with Runnable not when class extends Thread.
b.run();//This not run anything because no run method found in class B but it 
        //didn't show any error.

a.start();//this call run() of Thread
b.start();//this call run() of Thread
}

class A implements Runnable{
@Override
    public void run() {
            System.out.println("A ");
    }
}

class B extends Thread {

    @Override
    public void run() {
            System.out.println("B ");
    }
}

`


Actually Thread.start() creates a new thread and have its own execution scenario.

Thread.start() calls the run() method asynchronously,which changes the state of new Thread to Runnable.

But Thread.run() does not create any new thread. Instead it execute the run method in the current running thread synchronously.

If you are using Thread.run() then you are not using the features of multi threading at all.


In the first case you are just invoking the run() method of the r1 and r2 objects.

In the second case you're actually creating 2 new Threads!

start() will call run() at some point!


If you directly call run() method, you are not using multi-threading feature since run() method is executed as part of caller thread.

If you call start() method on Thread, the Java Virtual Machine will call run() method and two threads will run concurrently - Current Thread (main() in your example) and Other Thread (Runnable r1 in your example).

Have a look at source code of start() method in Thread class

 /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if (stopBeforeStart) {
            stop0(throwableFromStop);
        }
    }

    private native void start0();

In above code, you can't see invocation to run() method.

private native void start0() is responsible for calling run() method. JVM executes this native method.


Thread.start() code registers the Thread with scheduler and the scheduler calls the run() method. Also, Thread is class while Runnable is an interface.


run method : - is an abstract method originally created in the Runnable interface and overridden in the Thread class as well as Thread subclasses (As Thread implements Runnable in its source code) and any other implementing classes of Runnable interface. - It is used to load the thread (runnable object) with the task it is intended to do thus you override it to write that task.

start method : - is defined in Thread class. When start method is called on a Thread object 1- it calls internally native (nonjava) method called start0(); method.

start0(); method: is responsible for low processing (stack creation for a thread and allocating thread in processor queue) at this point we have a thread in Ready/Runnable state.

2- At a time when Thread scheduler decides that a thread enters a processor core acorrding to (thread priority as well as OS scheduling algorithm) run method is invoked on the Runnable object (whether it is the current Runnable thread object or the Runnable object passed to the thread constructor) here a thread enters a Running state and starts executing its task (run method)


The points, that the members made are all right so I just want to add something. The thing is that JAVA supports no Multi-inheritance. But What is if you want to derive a class B from another class A, but you can only derive from one Class. The problem now is how to "derive" from both classes: A and Thread. Therefore you can use the Runnable Interface.

public class ThreadTest{
   public void method(){
      Thread myThread = new Thread(new B());
      myThread.start;
   }
}

public class B extends A implements Runnable{...

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to multithreading

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Waiting until the task finishes What is the difference between Task.Run() and Task.Factory.StartNew() Why is setState in reactjs Async instead of Sync? What exactly is std::atomic? Calling async method on button click WAITING at sun.misc.Unsafe.park(Native Method) How to use background thread in swift? What is the use of static synchronized method in java? Locking pattern for proper use of .NET MemoryCache

Examples related to concurrency

WAITING at sun.misc.Unsafe.park(Native Method) What is the Swift equivalent to Objective-C's "@synchronized"? Custom thread pool in Java 8 parallel stream How to check if another instance of my shell script is running How to use the CancellationToken property? What's the difference between a Future and a Promise? Why use a ReentrantLock if one can use synchronized(this)? NSOperation vs Grand Central Dispatch What's the difference between Thread start() and Runnable run() multiprocessing.Pool: When to use apply, apply_async or map?

Examples related to runnable

In a simple to understand explanation, what is Runnable in Java? new Runnable() but no new thread? What's the difference between Thread start() and Runnable run() Naming threads and thread-pools of ExecutorService Runnable with a parameter? "implements Runnable" vs "extends Thread" in Java The difference between the Runnable and Callable interfaces in Java