• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt related to threads

 
Nirmal Kumar Boran
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
I am a bit confused in a program of threads .

Code :




Output :


Second ChildThread: Thread[demo,5,main]
Child thread1: Thread[Demo Thread1,5,main]
Main Thread: 5
Child Thread: 5
Child Thread1: 5
Main Thread: 4
Child Thread: 4
Child Thread1: 4
Main Thread: 3
Child Thread: 3
Child Thread1: 3
Main Thread: 2
Child Thread: 2
Child Thread1: 2
Main Thread: 1
Child Thread: 1
Child Thread1: 1
Main Thread: 0
Exiting child thread.
Exiting child1 thread.
Main thread exiting.


But I was expecting the first two lines of the output as.

Child thread1: Thread[Demo Thread1,5,main]
Second ChildThread: Thread[demo,5,main]

Because of the part of code
NewThread1()
{
t = new Thread(this, "Demo Thread1");
System.out.println("Child thread1: " + t);
t.start();
}
ChildThread C= new ChildThread();


We called child thread after the stmt "System.out.println("Child thread1: " + t);"
so should not it print "Child thread1: Thread[Demo Thread1,5,main]" before to "Second ChildThread: Thread[demo,5,main]
"

I might be wrong as I am in learning stage.
Can someone guide me where I am wrong.
Thanks in advance.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use code tags when posting your source. It preserves the indentation and make it easier to read.

I have edited your post to include them.

And welcome to the Ranch.
 
Henry Wong
author
Marshal
Pie
Posts: 21423
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nirmal Kumar Boran wrote:
But I was expecting the first two lines of the output as.

Child thread1: Thread[Demo Thread1,5,main]
Second ChildThread: Thread[demo,5,main]

Because of the part of code
NewThread1()
{
t = new Thread(this, "Demo Thread1");
System.out.println("Child thread1: " + t);
t.start();
}
ChildThread C= new ChildThread();


This is *not* a thread issue -- as both of those messages are constructor messages. In understand how those messages are printed, you should understand the calling order of constructors. And in this case, the demo thread completed construction, before the message of the newthread1 constructor print the message.

Henry

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic