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