/*模拟银行取钱*/- public class Account {
- //账户余额
- private double balance;
- public Account(double balance) {
- this.balance = balance;
- }
- /*取钱的方法*/
- public double drawBalance(double drawBalance)
- {
- balance = balance - drawBalance;
- return balance;
- }
- /*查询余额*/
- public double getBalance()
- {
- return balance;
- }
- }
复制代码 /*取钱的线程*/
public class DrawThread extends Thread
{
private Account a;
//要取的金额
private double drawBalance;
public DrawThread(String name, Account a, double drawBalance)
{
super(name);
this.a = a;
this.drawBalance = drawBalance;
}
public void run()
{
while(true){
synchronized(a){
if(a.getBalance() < drawBalance){
System.out.println(Thread.currentThread() + " : 余额不足,当前余额: " + a.getBalance());
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
a.drawBalance(drawBalance);
System.out.println(Thread.currentThread() + "取钱成功,取走金额:" + drawBalance + " ,当前余额:" + a.getBalance());
}
}
}
}
/*在主方法中运行*/- public class DrawTest {
- public static void main(String[] args) {
- Account a = new Account(1000);
- new DrawThread("A账户:", a, 500).start();
- new DrawThread("B账户:", a, 300).start();
- }
- }
复制代码 //当使用this或者其他对象作为锁的时候,为什么共享数据会出错?毕老爷说着个同步代码块的锁可以任意指定,我反复模拟了几个列子,都会出错,只有使用要操作的对象时作为锁时,测试结果才没问题
|