VOOZH about

URL: https://www.geeksforgeeks.org/java/run-method-in-java-thread/

⇱ run() Method in Java Thread - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

run() Method in Java Thread

Last Updated : 18 Dec, 2024

The run() method is available in the thread class constructed using a separate Runnable object. Otherwise, this method does nothing and returns. We can call the run() method multiple times. 

The run() method can be called in two ways which are as follows:

  1. Using the start() method.
  2. Using the run() method itself.

Syntax:

public void run() { 
 //statements 
} 

1. Using the start() method

We can use the start() method by using a thread object.

 Step 1: Create run method.

 Step 2: Create an object for the class.

Usingstart obj=new Usingstart();

 Step 3: Create a thread object by passing the class variable.

Thread t1 =new Thread(obj);

 Step 4: This will call the run() method.

t1.start();

Example:


Output
This thread is running

2. Using the run() method

We can use the run() method by using a thread object.

Step 1: Create run method.

Step 2: Create an object for the class. Syntax for creating object

Usingstart obj=new Usingstart();

Step 3: This will call the run() method. Syntax for running the thread.

obj.run();

Example:


Output
This thread is running

Calling run() Method Multiple Times 

In Java, we can also call the run() method multiple times. By using a for loop, we can call the same run method numerous times.

Example:


Output
Running 1 Time
Running 2 Time
Running 3 Time
Running 4 Time
Running 5 Time
Running 6 Time
Running 7 Time
Running 8 Time
Running 9 Time
Running 10 Time
Running 1 Time
Running 2 Time
Running 3 Time
Running 4 Time
Running 5 Time
Running 6 Time
Running 7 Time
Running 8 Time
Running 9 Time
Running 10 Time

Overloading the run() Method

We can also overload the run()method. By changing the parameters, we can get exact things from the methods.

Example: Java program that takes two overloaded methods with one parameter and another with no parameters.

Here we first call the parameter method and then call the no parameter method.


Output
single parameter method
no parameters method
Comment
Article Tags: