• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic