Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread: Not calling run method

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");

}
}
like image 527
NullPointer Avatar asked Jul 17 '26 14:07

NullPointer


2 Answers

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.)

like image 65
Jon Skeet Avatar answered Jul 20 '26 04:07

Jon Skeet


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();
like image 45
akaIDIOT Avatar answered Jul 20 '26 05:07

akaIDIOT