Java多线程同步中的两个特殊类
http://tech.ddvip.com 2006年11月25日 社区交流
本文详细介绍Java多线程同步中的两个特殊类
Your balance is:1000.0
withdraw:800.0
deposit:800.0
Your balance is:1000.0
Your balance is:1000.0
withdraw:800.0
withdraw:800.0
余额不足!
Your balance is:200.0
Your balance is:200.0
Your balance is:200.0
余额不足!
Your balance is:200.0
Your balance is:200.0
Your balance is:200.0
Your balance is:200.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
deposit:160.0
余额不足!
余额不足!
余额不足!
余额不足!
余额不足!
余额不足!
为什么会出现这样的情况?因为我们这儿是多个ATM同时对同一账户进行操作,比如一个ATM查询出了余额为1000,第二个ATM也查询出了余额1000,然后两者都期望提取出800,那么只有第1个用户能够成功提出,因为在第1个提出800后,账户真实的余额就只有200了,而第二个用户仍认为余额为1000。这个问题是由于多个ATM同时对同一个账户进行操作所不可避免产生的后果。要解决这个问题,就必须限制同一个账户在某一时刻,只能由一个ATM进行操作。如何才能做到这一点?直接通过synchronized关键字可以吗?非常遗憾!因为我们现在需要对整个Account的多个方法进行同步,这是跨越多个方法的,而synchronized仅能对方法或者代码块进行同步。
我们首先开发一个BusyFlag的类,类似于C++中的Simaphore。
public class BusyFlag
{
protected Thread busyflag = null;
protected int busycount = 0;
public synchronized void getBusyFlag()
{
while (tryGetBusyFlag() == false)
{
try
{
wait();
}
catch (Exception e) {}
}
}
private synchronized boolean tryGetBusyFlag()
{
if (busyflag == null)
{
busyflag = Thread.currentThread();
busycount = 1;
return true;
}
if (busyflag == Thread.currentThread())
{
busycount++; return true;
}
return false;
}
public synchronized void freeBusyFlag()
{
if(getOwner()== Thread.currentThread())
{
busycount--;
if(busycount==0)
{
busyflag = null;
notify();
}
}
}
public synchronized Thread getOwner()
{
return busyflag;
}
}
注:参考Scott Oaks & Henry Wong《Java Thread》
责编:豆豆技术应用