• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Thread

 
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.
 
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!
 
Sheriff
Posts: 11343
Mac Safari Java
  • 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 ]
 
I wasn't selected to go to mars. This tiny ad got in ahead of me:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
    Bookmark Topic Watch Topic
  • New Topic