Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Runnable's run() method directly on thread object [duplicate]

We cannot call Runnable's run() method directly on thread's object but according to the below program we are doing it without any compilation or Runtime errors. Why is it so?

public class ThreadCheck implements Runnable {

    @Override
    public void run() {
        for (int i=0; i<10; ) {
            System.out.println(++i);
        }
    }

    public static void main(String[] args) {
        Thread mythread = new Thread(new ThreadCheck());
        mythread.run();
        mythread.run();
        mythread.start();
    }   
}

Output: 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10

like image 585
Prateek Kar Avatar asked Jun 24 '15 15:06

Prateek Kar


People also ask

What will happen if we called run () method directly in thread?

If we call directly the run() method, it will be treated as a normal overridden method of a thread class (or runnable interface) and it will be executed within the context of the current thread, not in a new thread.

Can we call run method twice in thread?

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

Can we call run method directly in thread?

No, you can not directly call run method to start a thread. You need to call start method to create a new thread. If you call run method directly , it won't create a new thread and it will be in same stack as main.

Which method is executed when the start () method of a thread object is called?

New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed.


2 Answers

This will not have any compilation or run-time errors. But it also will not spawn new threads. It will execute the run() method in the current main thread.

refer what will happen if we directly call run method?

like image 116
KDP Avatar answered Oct 06 '22 08:10

KDP


We can call Runnable's run() method directly on thread's object. But, when you call run() method from thread's object, the run() method will work as a normal method. When you call it, it doesn't create a new thread.

In this case the run() method will be treated as a normal method call. But when you call the start() method on the Thread object, then it automatically calls the run() method on a new thread in the JVM.

like image 34
Puneet Chawla Avatar answered Oct 06 '22 07:10

Puneet Chawla