【发布时间】:2017-02-19 17:39:23
【问题描述】:
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));
}
}
});
}
当我运行上面的简单存款函数时,我希望两个线程不应该同时进入同步块。但操作顺序如下:
- Depo100
- Depo200
- 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 at 800
deposited 200 to funds. Now at 1000
我们可以看到两个线程同时进入同步块并访问了不期望的平衡对象。 我在这里做错了什么?我是多线程的新手。 提前致谢。
【问题讨论】:
-
balance每次都是不同的对象。没有相互排斥。 -
请注意,当您使用
+构建字符串时,您不需要调用Integer.toString(amt):字符串连接会自动为您执行此操作。
标签: java multithreading