Run() Method in Java
Run() Method in Java
In this article we will be discussing about run() method in Java.
The run() method that is available in the thread class is used to create a separate Runnable object. Otherwise, this method does nothing and returns.
Use of Run Method:
We can Call run function with the help of following methods:
- run() method
- Start() method
The code supplied in the run() method is performed when the run() function is called. The run() method can be used repeatedly.The run() method can be overloaded as well. We can achieve precise results from the approaches by adjusting the parameters.
Syntax:
public void run(){ // operations; }
Calling run Function by Itself
we can call run button by itself by creating the object of the thread class.
Example:
import java.util.*; class Main { // Function Definition public static void run(int count) { if (count == 0) { return; } System.out.println("Running the function: " + count); // Function calling itself run(count - 1); } public static void main(String[] args) { int count = 5; // Function calling run(count); } }
Output: Running the function: 5 Running the function: 4 Running the function: 3 Running the function: 2 Running the function: 1
Calling run function by using Start
we can call run method by using start() method by creating the object of the thread class and by creating a thread object by passing the class variable.
Example:
import java.util.*; // class definition class MyThread extends Thread { // function definition public void run() { System.out.println("In the run Function"); } } public class Main { public static void main(String[] args) { // Initializng the object of the class MyThread myThread = new MyThread(); // Function calling myThread.start(); } }
Output: In the run Function
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment