This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Volatile use with Synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Volatile use with Synchronization" Watch "Volatile use with Synchronization" New topic
Author

Volatile use with Synchronization

Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 232


i am running below code using volatile keyword but it gives result unexpected. it is working on two threads but not with the three.

if i am using two thread then it give output something like this:
Thread 1 : 1
Thread 2 : 1
Thread 1 : 2
Thread 2 : 2
Thread 1 : 3
Thread 2 : 3
Thread 1 : 4
Thread 2 : 4
Thread 1 : 5
Thread 2 : 5
............more

please tell me why this is not working in three thread?




SCJP 6- 91%, IBM DB2, IBM RAD Certified
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1752
    
    7

You should always wait() in a loop that test's if the wait condition is satisfied.
The two thread version is equally broken, by the way, because a thread can also wake up without being notified, which is called spurious wakeup.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 232

can you tell me from some other way
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Volatile use with Synchronization
 
Similar Threads
notifyAll
locking??
Synchronization Issue With Threads.
about threads, using locks of the objects in synchronized blocks
Need Explanation of unpredicted output even if methods are synchronized