Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
    Bookmark Topic Watch Topic
  • New Topic

Threads

 
Lalitha Vydyula
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Report post to moderator
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

Thanks,
-Lalitha

(Marilyn added code tags)
[ August 03, 2005: Message edited by: Marilyn de Queiroz ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Report post to moderator
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.
 
Marilyn de Queiroz
Sheriff
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Report post to moderator


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.
 
    Bookmark Topic Watch Topic
  • New Topic