Hi,

Aim of the below program is to access "balance" variable by only 1 synchronized block code. But, it is seen that synchronization is not working properly here. Pl, let me know how this program can work perfectly i.e. should not produce any output but run in infinite loop.

<code>

// BalanceUpdateSynchronized.java


public class BalanceUpdateSynchronized {
// Start with balance as 100
private static int balance = 100;

public static void main(String[] args) {
// Start two threads to update the balance
startBalanceUpdateThread();

// Start one thread to monitor the balance
startBalanceMonitorThread();
}

public static void startBalanceUpdateThread() {
// Start a new thread that calls updateBalance() method
Thread t = new Thread()
{
public void run() {
while (true) {


synchronized(this)
{
balance=balance+10;
balance=balance-10;
}


}
}
};
t.start();
}

public static void startBalanceMonitorThread() {
// Start a thread that monitors the balance value
Thread t = new Thread() {
public void run() {

while (true) {


synchronized(this)
{
int b = balance;
//Ideally, balance should not change and this program run in
// infinite loop
if (b != 100) {
System.out.println("Balance changed: " + b);
System.exit(1); // Exit the program
}

}

}
}
};
t.start();
}
}

</code>