Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

main thread child thread  RSS feed

 
Arun kumar Maalik
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class today extends Thread{

today(String str){
super(str);
}

public void run(){

for(int i=1;i<=10;i++){
System.out.println(i+" "+getName());

try{
Thread.sleep(500);
}
catch(InterruptedException e){}

}
}

public static void main(String[] args){

today p=new today("First");
today q=new today("Second");
Thread t=Thread.currentThread();
p.start();
q.start();

for(int i=1;i<=10;i++){
System.out.print(i+" "+t);
try{
Thread.sleep(500);
}
catch(InterruptedException e){}

}

}

}

Helo frnd in the above code first it is calling main thread then child thread why although we are calling p.start(),q.start() first, in other words i would like to know when does child threa created either after compilation of main thread or in between main thread.

with regard
Arun kumar maalik
 
Jan-Jaap van Nieuwkerk
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welli'll give it a try.
Beware! i am only a beginner.
I guess your real question is :
Why does the main thread execute first although you start the other two threads first.

As far as i understood you can not tell which thread will execute first.
When you change your program a bit (add a few extra threads)
like:


and you extend the range of the for loops you will probably see in your output that the order the threads are executed changes.

The why of it all will have to be explained by someone else

Oh and if my answer is wrong please correct me.

good luck

hope it helps a it (probably one of the experts will chime in now)
[EDIT] Look what i found on this site: JavaRanch thread example
[ July 07, 2006: Message edited by: Jan-Jaap van Nieuwkerk ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!