3

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

}
}
NullPointer
  • 152
  • 1
  • 16

3 Answers3

6

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I think in the very early days of Java there was a tendency to supply the run method by extending Thread, rather than passing a Runnable. That depended on Thread implementing Runnable, and therefore having a run method. – Patricia Shanahan Feb 11 '13 at 09:14
  • @PatriciaShanahan: Absolutely - it was a bad idea then, too :) It's nice that best practice has moved on... it's a shame that we're stuck with badly-designed libraries forever... – Jon Skeet Feb 11 '13 at 09:15
2

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();
akaIDIOT
  • 9,171
  • 3
  • 27
  • 30
0

You can also do it this way.Do not implement Runnable in your main class, but create an inner class within your main class to do so:

class TestRunnable implements Runnable{
    public void run(){
        System.out.println("Thread started");
   }
}

Instantiate it from your Main class inside the main method:

TestRunnable test = new TestRunnable(); 
Thread thread = new Thread(test);
thread.start();
Poonam Anthony
  • 1,848
  • 3
  • 17
  • 27