I am new in java. Can someone help me why it is not calling Run method. Thanks in advance.
package com.blt;
public class ThreadExample implements Runnable {
public static void main(String args[])
{
System.out.println("A");
Thread T=new Thread();
System.out.println("B");
T.setName("Hello");
System.out.println("C");
T.start();
System.out.println("D");
}
public void run()
{
System.out.println("Inside run");
}
}
You need to pass an instance of ThreadExample to the Thread constructor, to tell the new thread what to run:
Thread t = new Thread(new ThreadExample());
t.start();
(It's unfortunate that the Thread class has been poorly designed in various ways. It would be more helpful if it didn't have a run() method itself, but did force you to pass a Runnable into the constructor. Then you'd have found the problem at compile-time.)
The run method is called by the JVM for you when a Thread is started. The default implementation simply does nothing. Your variable T is a normal Thread, without a Runnable 'target', so its run method is never called. You could either provide an instance of ThreadExample to the constructor of Thread or have ThreadExample extend Thread:
new ThreadExample().start();
// or
new Thread(new ThreadExample()).start();
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