The output :
F:\JavaPrograms\THREAD>java TestThread1
Second Thread
First Thread
1
Second Thread
1
First Thread
2
Second Thread
2
First Thread
3
Second Thread
3
First Thread
4
Second Thread
4
First Thread
5
Second Thread
5

My Questions :
[a] Second thread starts run() prints "Second Thread", goes to sleep. First
thread starts run(), prints "First Thread" and goes to sleep. "Second
Thread" wakes up by this time, prints count [1], then prints it's name
"Second Thread", goes to sleep. "First Thread" starts, from where it left,
in for loop, prints count[1], prints it's name, goes to sleep.
Am I right thus far ?
Is it separate instances of run() method for the thread1 and thread2, that
we are seeing "own" count values ?

The output :
F:\JavaPrograms\THREAD>java TestThread3
Second Thread
First Thread
1
Second Thread
1
First Thread
2
Second Thread
2
First Thread
3
Second Thread
3
First Thread
4
First Thread
4
Second Thread
5
First Thread
5
Second Thread

[b] The output is on expected line, even removing sleep (as always mentioned
in demo examples). If the threads are of same priority, why one thread
needs to be slept in order to awaken the other ? Alternate
pattern is maintained thruout, except a repetition of "First Thread" - is
that explainable or just a glitch of OS ?

Second Thread
1
Second Thread
2
Second Thread
3
Second Thread
4
Second Thread
5
Second Thread
6
Second Thread
7
Second Thread
8
Second Thread
9
Second Thread
10
Second Thread
........
Second Thread
53
Second Thread
First Thread
1
First Thread
2
First Thread
3
54
Second Thread
55
Second Thread
56
Second Thread
57
Second Thread
58
Second Thread
59
Second Thread
60
....
Second Thread
90
Second Thread
91
Second Thread
92
Second Thread
93
....
and no more "First Thread" seen. Is this on expected line ? I was expecting a mix of alternate threads, with more of "Second Thread". I am in favor of avoiding sleep to see how JVM takes care of naturally.

Thanks.
Atanu

10-14-2009, 06:07 PM

Atanu_Banerjee

Thread Basics

Hi Rohit :

One more observation. Changing the following, makes no difference in output, to the last one.