• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

simple Thread creation

 
rekha devan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
// Implementing one thread.

class RunnableThread implements Runnable
{
private int iThreadCount;

private Thread threadObj;

RunnableThread()
{
iThreadCount++;
threadObj = new Thread("Thread" + iThreadCount);
System.out.println("threadObj : " + threadObj);
threadObj.start();

}

public void run()
{

System.out.println("In the run method");
for(int i = 0; i<5; i++)
{
System.out.println(i + " : " + threadObj.getName());
}
System.out.println("***Exiting the run method***");

}


}

public class TestRunnableThread
{
public static void main(String args[])
{

RunnableThread simpleThread = new RunnableThread();
System.out.println("***Exiting main method***");

}

}

In the above program the run method is never executed can anyone explain why?

What I understand is the main Thread exits after creation of the child thread. But the child thread would continue to execute till its process is complete. Then why is the control not going to the run method?


Thanks,
Rekha
 
srikanth reddy
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i feel that threadObj = new Thread("Thread" + iThreadCount);
has problem as we need to pass the runnablethread instance inorder to execute the run method..instead ur passing a class variable...

/****
Runnablethread rt= new Runnablethread();
Thread t=new Thread(rt);
t.start();
/***


thanks
sri
 
rekha devan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, it is working!!

Yes i forgot to mention the runnable object in the thread constructor.
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
threadObj = new Thread("Thread" + iThreadCount);

This line creates a new instance of a threadclass & has it's own run method ( default method ).
But if you pass a runnable object to the thread constructor then the Runnable becomes the target of this thread.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic