Příklad

public static class Base {
public synchronized void setValue( int value ) {
try { Thread.sleep( 1000 ); } catch (InterruptedException e) {}
this .value = value;
}
public synchronized int getValue() {
return value;
}
protected int value = 0;
}

public static class Derived extends Base {
public int getValue() {
return this .value;
}

}

public static void main(String[] args) {
System.out.println( "Testing Base..." ); //$NON-NLS-1$
test( new Base() );
try { Thread.sleep( 5000 ); } catch (InterruptedException e) {}
System.out.println( "Testing Derived..." ); //$NON-NLS-1$
test( new Derived() );
}

private static void test( final Base base ) {
Runnable writer = new Runnable() {
public void run() {
System.out.println( "Writer set value " ); //$NON-NLS-1$
base.setValue( 1 );
}
};

Runnable reader = new Runnable() {
public void run() {
System.out.println( "Reader: " + base.getValue() ); //$NON-NLS-1$
}
};

(new Thread( writer ) ).start();
(new Thread( reader ) ).start();
}

Řešení
Změňte metodu potlačení, aby byla synchronized.

public static class Base {
public synchronized void setValue( int value ) {
try { Thread.sleep( 1000 ); } catch (InterruptedException e) {}
this .value = value;
}
public synchronized int getValue() {
return value;
}
protected int value = 0;
}

public static class Derived extends Base {
public synchronized int getValue() {
return this .value;
}

}

public static void main(String[] args) {
System.out.println( "Testing Base..." ); //$NON-NLS-1$
test( new Base() );
try { Thread.sleep( 5000 ); } catch (InterruptedException e) {}
System.out.println( "Testing Derived..." ); //$NON-NLS-1$
test( new Derived() );
}

private static void test( final Base base ) {
Runnable writer = new Runnable() {
public void run() {
System.out.println( "Writer set value " ); //$NON-NLS-1$
base.setValue( 1 );
}
};

Runnable reader = new Runnable() {
public void run() {
System.out.println( "Reader: " + base.getValue() ); //$NON-NLS-1$
}
};

(new Thread( writer ) ).start();
(new Thread( reader ) ).start();
}