private static Integer balance=0;
public static void deposit(final int amt) {
Thread t = new Thread(new Runnable() {
public void run() {
synchronized(balance) {
System.out.println("Balance at start is: "+balance);
balance+=amt;
System.out.println("deposited " + Integer.toString(amt) + " to funds. Now at " + Integer.toString(balance));
}
}
});
}
When I run the above simple deposit function, I expect that two threads should not enter at same time in synchronized block. But with operation Sequence as below:
- Depo100
- Depo200
- Depo700
Output is as below:
------------------
Balance at start is: 0
deposited 100 to funds. Now at 100
Balance at start is: 100
Balance at start is: 100
deposited 700 to funds. Now at 800
deposited 200 to funds. Now at 1000
As we can see two threads entered at same time in the synchronized block and accessed balance object which is NOT expected. What I am doing wrong here ? I am newbie for Multithreading. Thanks in advance.