This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads" Watch "Threads" New topic
Author

Threads

cyril vidal
Ranch Hand

Joined: Jul 02, 2003
Posts: 247
Dear all,
It looks me a little odd...
Here's the following code:

On my computer, I have always ABC as output.
When I modify the code as follow:

now the output is always XYZ
I'm little surprised, because normally adding

shouldn't change anything. It says only the C.main Thread to wait for 0 milliseconds.
Or, here, all happens as the main method was waiting for more time, so that sa String's array doesn't change and is printed in its first form.
Can someone explain me what's happening?
Thanks in advance,
Cyril.


SCJP 1.4, SCWCD, SCBCD, IBM XML, IBM Websphere 285, IBM Websphere 287
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443




Hi Cyril,
I think both of your codes(original and modified) will not guarantee a consistent output. They don't lock anything.
[ July 08, 2003: Message edited by: Alton Hernandez ]
[ July 08, 2003: Message edited by: Alton Hernandez ]
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
Can someone explain me what's happening?

In your first example, when you test the program, the first thread executes the entire main method before the second thread executes the run method.
*Occasionally* the virtual machine *might* decide to preempt the first thread and let the second thread execute. The virtual machine might preempt the first thread after it has executed only a few lines of the main method.
In your second example, when you test the program, the first thread invokes the sleep method. The thread does not sleep, but the virtual machine decides to preempt that thread and let the second thread execute.
When I play with Dan�s thread examples, I add Thread.yield(); at various places in the code to encourage the virtual machine to preempt the currently executing thread and let the other thread run. That way I can see more than one possible way the virtual machine might schedule the threads.
I also sometimes add print statements, to see the order the threads execute, although the I/O might also affect the thread scheduling.
cyril vidal
Ranch Hand

Joined: Jul 02, 2003
Posts: 247
OK, thanks for your clear explanations.
Cyril.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads
 
Similar Threads
Synchronized Objects
wait/notify
Dan's: Thread Q 39
Thread - Wait Doubt
Thread