Dushyant Suthar Dushyant Suthar - 5 months ago 8
Android Question

Why run() method defined is not called on call of start by Thread?

I was just experimenting some code around Thread class and I get stuck at something, Well firstly have a look at my code

class ThreadExample implements Runnable
{
String threadName;
Thread thread;
public ThreadExample()
{
thread=new Thread();
thread.start();
}
public void run()
{
System.out.println("Thread "+getThreadName()+" is being executed");
}
void setThreadName(String string)
{
threadName=string;
thread.setName(string);
}
String getThreadName()
{
return thread.getName();
}
public static void main(String string[]) throws InterruptedException
{
ThreadExample threadExample= new ThreadExample();
threadExample.setThreadName("Thread !");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 2");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 3");
Thread.sleep(500);
}
}


Well I think this code is very simple and Everyone should have got my intentions although When I am running this program It just get complete without even calling
run()
method even I make main Thread to wait for sometime until the child Thread which is ThreadExample completes. I am new to this so sorry if I have forgotten some thing. Thanks in advance.

Answer

You created a Runnable type and never passed it into a thread context. You'll want to add it to the Thread. I would do something like:

String threadName;
Thread thread;
public ThreadExample() {
    thread=new Thread(this);
}

public void startThread() {
   thread.start();
} 

The Thread class accepts a Runnable as an argument.