Cover Image for Calling run() method
127 views

Calling run() method

The Java call the run() method of a class that extends Thread, just like you would call any other method. However, calling the run() method directly does not create a new thread of execution; it simply invokes the method in the current thread. This is different from calling the start() method, which creates a new thread and then invokes the run() method within that new thread.

Here’s a simple example to illustrate calling the run() method:

public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Thread is running... (Iteration " + i + ")");
        }
    }

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

        // Calling run() directly will not create a new thread
        thread.run();

        // The following line will run the run() method in the main thread
        System.out.println("Main thread is running...");
    }
}

In this example, we create an instance of the MyThread class and call its run() method directly. As a result, the run() method is executed in the main thread, not in a new thread. The output will show that the “Thread is running…” messages and the “Main thread is running…” message are interleaved because they are all executed in the main thread.

To create a new thread and execute the run() method in that new thread, you should call the start() method, as follows:

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

    // Calling start() creates a new thread and runs the run() method in that thread
    thread.start();

    // The following line will run in the main thread
    System.out.println("Main thread is running...");
}

In this case, when you call thread.start(), it creates a new thread, and the run() method is executed in that new thread, while the main thread continues to execute independently. This allows concurrent execution of the “Main thread is running…” message and the “Thread is running…” messages.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS