小编cra*_*ead的帖子

Synchronized()块未按预期工作

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块中同时进入.但是操作顺序如下:

  1. Depo100
  2. Depo200
  3. Depo700

输出如下:

------------------
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)

java multithreading

4
推荐指数
1
解决办法
139
查看次数

标签 统计

java ×1

multithreading ×1