Posted By:
Chris_Adams
Posted On:
Friday, August 17, 2001 06:16 AM
Anyone notice that the Trail: Essential Java Classes Lesson: Threads: Doing Two or More Tasks At Once - The Producer/Consumer Example produces random results when the author states - "When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked." The results show this not the case: He says the results will be: Producer #1 put: 0 Consumer #1 got: 0 Producer #1 put: 1 Consumer #1 got: 1 Producer #1 put: 2 Consumer #1 got: 2 Producer #1 put: 3 Consumer #1 got: 3 Producer #1
More>>
Anyone notice that the Trail: Essential Java Classes Lesson: Threads: Doing Two or More Tasks At Once -
The Producer/Consumer Example produces random results when the author states -
"When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked."
The results show this not the case: He says the results will be:
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
Hence showing that the consumer is never invoked until the Producer is finished, but my results are random in order - sometimes the consumer consumes prior to the producer - how can this be?
my results:
Consumer #1 got: 0
Consumer #1 got: 1
Producer #1 put: 1
Consumer #1 got: 2
Producer #1 put: 2
Producer #1 put: 3
Consumer #1 got: 3
Consumer #1 got: 4
Producer #1 put: 4
Producer #1 put: 5
Consumer #1 got: 5
Consumer #1 got: 6
Producer #1 put: 6
Producer #1 put: 7
Consumer #1 got: 7
Consumer #1 got: 8
Producer #1 put: 8
Producer #1 put: 9
Consumer #1 got: 9
try for yourselves:
http://java.sun.com/docs/books/tutorial/essential/threads/synchronization.html
<<Less