java - Synchronizaton Object Lock Confusion -
i studying k&b threads chapter. reading synchronization. here example 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 overdrawn"); } } } public static void main(string[] args){ accountdanger accountdanger = new accountdanger(); thread 1 = new thread(accountdanger); thread 2 = 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() + " going withdraw"); try{ thread.sleep(500); } catch(interruptedexception e) { e.printstacktrace(); } account.withdraw(amt); system.out.println(thread.currentthread().getname() + " completes withdrawl"); } else{ system.out.println("not enough in account " + thread.currentthread().getname() + " withdraw " + account.getbalance()); } } }
k&b talks synchronized methods , synchronized blocks. here referring paragraph k&b.
when method executing code within synchronized block, code said executing in synchronized context. when synchronize method, object used invoke method object lock must acquired. when synchronize block of code, must specify object's lock want use lock.
so in example, lock acquired on accountdanger instance or account object? think should accountdanger. perceiving correct? if accountdanger object, , 1 thread has got lock of accountdanger, other thread able call non-synchronized methods?
so in example, lock acquired on accountdanger instance or account object?
yes. 1 trick i've seen used lot synchronize on this
when have small block of code needs synchronized. example:
int balance = -1; synchronized(this) { balance = account.getbalance(); account.withdraw(amt); } //io, etc. after that.
in general speeds things up.
Comments
Post a Comment