aspose file tools*
The moose likes Beginning Java and the fly likes Doubt related to threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt related to threads" Watch "Doubt related to threads" New topic
Author

Doubt related to threads

Nirmal Kumar Boran
Greenhorn

Joined: May 25, 2010
Posts: 1
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

Joined: Oct 02, 2003
Posts: 11314
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18840
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt related to threads