What is the difference between Thread.start() and Thread.run() in java?

What is the difference between Thread.start() and Thread.run() in java?

In Java, both Thread.start() and Thread.run() are methods of the Thread class, but they serve very different purposes and have different behaviors:

Thread.start()

  • Starting a New Thread: When you call the start() method on a Thread object, it initiates a new thread of execution. The JVM schedules this new thread to run, and the thread begins its execution by calling its run() method. This means that the code inside the run() method will execute concurrently with other threads.

  • Concurrency: Using start() allows the program to perform multiple tasks simultaneously. It is the correct way to start a new thread that will execute independently.

  • Single Execution: It's important to note that you can't start a thread more than once. Attempting to call start() on a thread that has already started or finished execution will result in a java.lang.IllegalThreadStateException.

Thread.run()

  • Calling run() Directly: When you call the run() method directly on a Thread object, you are not starting a new thread. Instead, the run() method executes in the current thread, just like a normal method call. There is no concurrency or new thread of execution.

  • Same as Normal Method Call: Calling run() is no different from calling any other method. The code inside run() will execute sequentially in the current thread and will not create a new thread.

Example

Let's look at a simple example to illustrate the difference:

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Running in " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        MyThread t = new MyThread();

        t.start(); // Starts a new thread; will output something like "Running in Thread-0"

        t.run(); // Executes in the main thread; will output "Running in main"
    }
}

In this example, calling t.start() starts a new thread and executes run() in that new thread, while calling t.run() directly just executes run() in the main thread.

Conclusion

  • Use Thread.start() when you want to start a new thread and execute code concurrently.
  • Calling Thread.run() directly does not start a new thread; it just executes the run() method in the current thread.

More Tags

android-browser html-lists environment exit xamarin.mac itunes fasta compiler-errors hittest yii-extensions

More Java Questions

More General chemistry Calculators

More Weather Calculators

More Animal pregnancy Calculators

More Biology Calculators