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 streams should not be entered simultaneously in the synchronized block. But with the sequence of operations as shown below:
The output is as follows:
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 streams entered at the same time in the synchronized block and an available balance object, which is NOT expected. What am I doing wrong here? I am new to Multithreading. Thanks in advance.
source
share