public class Test {
public static void main(String[] args) {
Account account=new Account(100);
Person p1=new Person(account,80);
Person p2=new Person(account,90);
p1.start();
p2.start();
}
}
class Account{
int total;
public Account(int total) {
super();
this.total=total;
}
}
class Person extends Thread{
private int reduce;
public Account account;
public Person(Account account,int reduce) {
this.account=account;
this.reduce=reduce;
}
public synchronized void run() {
if (account.total-reduce<0) return ;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
account.total-=reduce;
System.out.println(Thread.currentThread().getName()+"取出"+reduce);
System.out.println(Thread.currentThread().getName()+"剩余"+account.total);
}
}
Thread-0取出80Thread-0剩余-70Thread-1取出90Thread-1剩余-70
這里是模擬的從賬戶取錢的操作,是用的同步方法,但是這里鎖失敗了。我看別人說是account沒鎖住,但是account也是person對象的成員啊,同步方法不是把person對象鎖住了嗎,為什么這里沒上鎖呢?
2 回答

不負相思意
TA貢獻1777條經驗 獲得超10個贊
已經解決了,每個對象都有一個監視器查看是否上鎖,person對象有,account對象也有,person對象上鎖并不能影響到account的鎖,這也就是為什么account沒被鎖住的原因,p1進入方法后,p2再進入是查看account的監視器,沒有鎖,成功進入。所以說沒有鎖住。這里需要的是account的鎖。
public void run() {
synchronized(account) {
if (account.total-reduce<0) return ;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
account.total-=reduce;
System.out.println(Thread.currentThread().getName()+"取出"+reduce);
System.out.println(Thread.currentThread().getName()+"剩余"+account.total);
}
}
添加回答
舉報
0/150
提交
取消