• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread

 
sai donthneni
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question in this program.
public class TwoThread extends Thread
{

public void run()
{
for(int i=0;i<10;i++)
printMsg();
}
public void printMsg()
{
Thread t=Thread.currentThread();
String name=t.getName();
System.out.println("name:"+name);

}

public static void main(String args[])
{
TwoThred tt=new TwoThread();
tt.setName("Child Thread");
tt.start();

for(int i=0;i<10;i++)
tt.printMsg();
}
}

when tt.printMsg() from main is executed the main htread is being displayed. Why is this so.... why is not the child thread being displayed since thread ojext tt creates a new thread.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Threads execute code. What thread executes main? The thread named main. That thread executes tt.printMsg. In that call, the current thread is main!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the loop in the main thread, the reference to tt is simply being used to call the method printMsg(). Calling this method on a Thread object is no different than calling a method on a non-Thread object -- it's just an instance method.

The separate thread is initiated by calling start(), and the code that executes in that thread is contained within the run() method.

(Note: Please use Code Tags to keep your code formatting intact.)
[ March 28, 2006: Message edited by: marc weber ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic