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 take out 80
Thread-0 remaining-70
Thread-1 take out 90
Thread-1 remaining-70
here is a simulated operation of withdrawing money from an account, using the Synchronize method, but the lock failed. I think people say that account is not locked, but
account is also a member of the person object. Doesn"t the Synchronize method lock the person object? why is it not locked here?