Results 1 to 3 of 3
- 03-11-2011, 09:16 PM #1
Member
- Join Date
- Mar 2011
- Posts
- 2
- Rep Power
- 0
synchronization doesn't seem to work
Hi,
I tried testing synchronization with the following code:
public class InterferenceFix extends Thread
{
String name;
static boolean isZero = true;
static int counter = 0;
public static void main(String arg[])
{
InterferenceFix one = new InterferenceFix("one");
InterferenceFix two = new InterferenceFix("two");
one.start();
two.start();
}
InterferenceFix(String nameString)
{
name = nameString;
}
public void run() {
for(int i=0; i<100000000; i++)
{
update();
}
System.out.println(name + ": " + counter);
}
synchronized void update()
{
if(isZero) {
isZero = false;
counter++;
} else {
isZero = true;
counter--;
}
}
}
the counter should be be 0 or 1 in both threads. Sometimes I get this result,
but sometimes different (plus or minus a few hundred).
Can anyone explain to me why synchronization doesn't work here?
thanks
- 03-11-2011, 09:30 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,379
- Blog Entries
- 7
- Rep Power
- 17
The synchronized keyword for a method synchronizes on 'this', i.e. the object that executes the method; in your example the one and two objects synchronize on the objects 'one' and 'two' respectively which is not what you want. Create a separate object, make it known to your objects and make them synchronize on that shared object.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 03-11-2011, 10:44 PM #3
Member
- Join Date
- Mar 2011
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
Thread synchronization
By rajanis in forum Threads and SynchronizationReplies: 0Last Post: 01-07-2011, 07:38 AM -
Synchronization Problem
By T3X4S in forum New To JavaReplies: 0Last Post: 09-17-2010, 05:35 AM -
Animation Synchronization
By dreadrocksean in forum Advanced JavaReplies: 5Last Post: 08-08-2008, 02:56 AM -
synchronization question
By oguz in forum Threads and SynchronizationReplies: 2Last Post: 07-22-2008, 08:56 AM -
Synchronization Doesn't seem to work
By sherinpearl in forum Threads and SynchronizationReplies: 1Last Post: 04-23-2008, 06:30 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks