一道面试题,好像是这样的
public class Account { int balance = 100; synchronized void draw(int num) {
this.balance = balance - num;
} void other(int num) {
draw(-num);
} public void test(Account from, Account to, int num) {
from.draw(num);
to.other(num);
}}并发下会出现什么问题,问题出现在哪一步
public class Account { int balance = 100; synchronized void draw(int num) {
this.balance = balance - num;
} void other(int num) {
draw(-num);
} public void test(Account from, Account to, int num) {
from.draw(num);
to.other(num);
}}并发下会出现什么问题,问题出现在哪一步
解决方案 »
- 漫谈equals方法(欢迎讨论)
- StaticDemo问题,程序有点看不懂
- Random()的用法问题.
- 一个字符串数组的白痴问题
- JDK安装 视频教程
- 请教连sql server2000的出现 jdbc connection reset by peer:socket write error
- 【JAVA】【张孝祥Java视频教程】
- oci方式访问数据库,url如何写?是否把oci805jdbc.dll放到oracle_home\bin下就可以了?
- 动画与media包的问题!
- 那里有JBuilder5的教程下载?
- 怎么用复选框 实现单选按钮的功能
- java图形界面,如何将单选框和复选框设为背景透明?
draw(-num);
}
this.balance = balance - num;
现在也不记得怎么不好了,所以我一直都用lock。
l.lock();
try {
this.balance = balance - num;
} finally {
l.unlock();
}
大哥!问题不在这里啊!lock();加这里还是有问题
我觉得应该是other这方法里的num变量,因为就它没有同步。。
首先 public void test(Account from, Account to, int num) 接收进来的from跟to是不同对象.内部的balance肯定不存在变量安全问题.
然后调用的void draw(int num)又加了同步锁,真看不出有什么问题.楼主,如果你当时说,没问题.估计他们老板就要你了,我也是猜的,哈哈哈,等高手来看
from.draw(num);
to.other(num);
}
如果from帐号没有足够的钱,还是会转去to帐号。明显没有对嘛。如果有多个线程同时运行,就更明显了。
可能from帐号被扣掉了1000,to帐号还没有到帐。也就是说,转账的操作,需要对两个帐号进行同步操作。
public void test(Account from, Account to, int num) {
from.draw(num);
to.other(num);
}其中的参数据Account from和Account to 是二个不同的对象,它们都只操作了自己的方法。
draw(-num);
}