my dog learned polymorphism
The moose likes Beginning Java and the fly likes Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic


Lalitha Vydyula
Ranch Hand

Joined: Jul 20, 2005
Posts: 69
Hi all,
Can anyone explain the flow of the below code. I'm really confused. Your help will be appreciated.

Here is the output
Child Thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread
Main Thread: 2
Main Thread: 1
Main thread exiting


(Marilyn added code tags)
[ August 03, 2005: Message edited by: Marilyn de Queiroz ]
marc weber

Joined: Aug 31, 2004
Posts: 11343

What is it specifically that you're confused about?

Basically, there are 2 threads here running concurrently. Each counts down from 5 to 1, sleeping a set (minimum) amount of time with each iteration. One thread tends to sleeps longer than the other, so it will likely take longer to finish running.

However, the exact output is unpredictable, because how the threads actually end up running is determined by the (platform-dependent) thread scheduler. In fact, you're likely to see different output from one execution to the next.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059

Line 1 creates a new NewThread which calls the constructor in line 5
The constructor makes another Thread labelled "Demo Thread" in line 6.
Line 7 prints the thread created in line 6.
Line 8 calls the run() method on the thread in line 6.
The constructor exits and line 2 starts a loop to print (line 3) the thread that is running main() which is a separate thread than the one created in the NewThread constructor. The loop waits 1 second between each println call (line 4).
Meanwhile the run() method begins a loop (line 10) to print (line 11) the thread created in line 5 waiting 1/2 second between each println call (line 12).
The rest is to demonstrate that the two loops (and the two threads) are running independently of each other. The results may vary (or not) each time you run the program.

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
I agree. Here's the link:
subject: Threads
jQuery in Action, 3rd edition