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
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.
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.
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.
New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed.
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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With