Reputation: 152
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");
}
}
Upvotes: 3
Views: 6502
Reputation: 1998
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();
Upvotes: 0
Reputation: 9231
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();
Upvotes: 2
Reputation: 1504162
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.)
Upvotes: 6