我正在学习 K&B 线程章节。我正在阅读有关同步的内容。这是 K&B 的一个例子。
public class AccountDanger implements Runnable {
private Account account = new Account();
public void run() {
for(int x =0 ; x < 5 ; x++){
makeWithdrawl(10);
if(account.getBalance() < 0 ){
System.out.println("account is overdrawn");
}
}
}
public static void main(String[] args){
AccountDanger accountDanger = new AccountDanger();
Thread one = new Thread(accountDanger);
Thread two = new Thread(accountDanger);
one.setName("Fred");
two.setName("Lucy");
one.start();
two.start();
}
private synchronized void makeWithdrawl(int amt){
if(account.getBalance() >= amt){
System.out.println(Thread.currentThread().getName() + " is going to withdraw");
try{
Thread.sleep(500);
}
catch(InterruptedException e) {
e.printStackTrace();
}
account.withdraw(amt);
System.out.println(Thread.currentThread().getName() + " completes the withdrawl");
}
else{
System.out.println("Not enough in account for " + Thread.currentThread().getName() + " to withdraw " +
account.getBalance());
}
}
}
K&B 谈到了同步方法和同步块。这是K&B的参考段落。
当一个方法在同步块中执行代码时,代码被称为在同步上下文中执行。同步方法时,调用该方法的对象就是必须获取锁的对象。但是当我们同步代码块时,您必须指定要使用哪个对象的锁作为锁。
那么在这个例子中,会在 AccountDanger 实例或 Account 对象上获取锁吗?我认为应该是AccountDanger。我的看法正确吗?如果是 AccountDanger 对象,并且一个线程获得了 AccountDanger 的锁,那么其他线程是否可以调用非同步方法?