David Holmes wrote:
> Jeremy,
>> Now you've confused me :)
I do seem to be doing more harm than good here... :)
>> If, on the other hand, the print() method assigns a value to y before
>> the println() statement, thus:
>>>> public void print() {
>> y = 42;
>> System.out.println(y);
>> }
>>>> then the same program would either print out 10 or 42, but not 0.
>> Ummm if the assignment occurs in the print method then the subsequent
> println must print 42 regardless because the assignment occurred in the same
> thread.
This is why I don't like the way we've been phrasing this example. We
haven't actually been showing both threads. I'll do it a little
differently (Maybe this will clarify?). If the class is this:
public class A{
private int x = 10;
public static A a;
public void foo(){
x = 20;
synchronized(this){
System.out.println( x );
}
}
public void bar(){
synchronized(this){
System.out.println( x );
}
}
}
This is one of the examples we have been discussing:
Thread 1:
A o = new A();
A.a = o;
Thread 2:
A r1 = A.a;
assert r1 != null;
r1.foo(); // can print out 10 or 20
This is the other:
Thread 1:
A o = new A();
A.a = o;
Thread 2:
A r1 = A.a;
assert r1 != null;
A r1.bar(); // can print out 10 or 0
Jeremy