我正在學習K & B線程章節。我正在閱讀關於同步。下面是從 ķ& B.Synchronizaton Object Lock Confusion
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());
}
}
}
ķ&約同步方法和同步塊B的會談的例子。這裏選自K & B.
當方法是從同步塊內執行的代碼段引用,代碼 據說以同步的上下文中執行。當您同步一個方法時,用於調用該方法的對象是必須獲取其鎖定的對象 。但是,當我們同步代碼塊 時,您必須指定要將哪個對象的鎖用作鎖。
所以在這個例子中,將在AccountDanger實例或Account對象上獲取鎖嗎? 我認爲應該是AccountDanger。我覺得正確嗎?如果它是AccountDanger對象, 和一個線程獲得了AccountDanger的鎖定,那麼其他線程是否可以調用非同步方法?
是的,它在AccountDanger對象上(隱式地,因爲該方法具有synchronized關鍵字)。 – Kayaman
謝謝卡亞曼。那麼這是否意味着一個線程獲取了當前對象的鎖定,其他線程無法訪問任何其他非同步方法? – benz
否。這意味着其他線程無法訪問其他同步方法。非同步方法可以被訪問,因爲它們沒有被對象監視器保護。 – Kayaman