Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads

 
cyril vidal
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Alton Hernandez
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




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
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, thanks for your clear explanations.
Cyril.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic