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));
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
当我运行上面的简单存款函数时,我希望两个线程不应该在synchronized块中同时进入.但是操作顺序如下:
输出如下:
------------------
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 …Run Code Online (Sandbox Code Playgroud)