Use of Java Thread start() and run() Methods

Java | Thread start() vs run() Methods: In this tutorial, we will see the differences between run() method and start() method of Thread class and which method we need to call in which case. Submitted by Saranjay Kumar, on March 23, 2020

Thread start() and run()

When we call the start() method, it leads to the creation of a new thread. Then, it automatically calls the run() method. If we directly call the run() method, then no new thread will be created. The run() method will be executed on the current thread only.

That is why we have the capability of calling the run method multiple times as it is just like any other method we create. However, the start() method can only be called only once.

Example 1

Consider the following code:

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

public class MyProg {
  public static void main(String[] args) {
    MyThread t1 = new MyThread();
    t1.start();
  }
}

Output

Thread Running: Thread-0

We can clearly see that the run() method is called on a new thread, default thread being named Thread-0.

Example 2

Consider the following code:

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

public class MyProg {
  public static void main(String[] args) {
    MyThread t1 = new MyThread();
    t1.run();
  }
}

Output

Thread Running: main

We can see that in this case, we call the run() method directly. It gets called on the current running thread -main and no new thread is created.

Similarly, in the following code, we realize that we can call the start method only once. However, the run method can be called multiple times as it will be treated as a normal function call.

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

public class MyProg {
  public static void main(String[] args) {
    MyThread t1 = new MyThread();
    t1.run();
    t1.run();
    t1.start();
    t1.start();
  }
}

Output

Thread Running: main
Thread Running: main
Thread Running: Thread-0

Exception in thread "main" java.lang.IllegalThreadStateException
	at java.base/java.lang.Thread.start(Thread.java:794)

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.