I know that
When you synchronize a code block, you specify which object lock you want to use as a lock, so that you can, for example, use some third-party object as a lock for this code fragment. This gives you the ability to have more than one lock to synchronize code within a single object.
However, I do not understand the need to pass an argument to a block. Since it doesn't matter if I pass in an instance of String, some case of a random class for a synchronized block, since the synchronized block works fine, regardless of the parameter passed to the block.
So my question is , if in any case the synchronized block stops two threads from entering the critical section at the same time. Then why is it necessary to pass an argument. (I mean, by default, locks on some random object).
I hope I correctly formulated my question.
I tried the following example with random parameters related to a synchronized block.
public class Launcher { public static void main(String[] args) { AccountOperations accOps=new AccountOperations(); Thread lucy=new Thread(accOps,"Lucy"); Thread sam=new Thread(accOps,"Sam"); lucy.start(); sam.start(); } }
Using a non-static synchronized block:
public class AccountOperations implements Runnable{ private Account account = new Account(); public void run(){ for(int i=0;i<5;i++){ makeWithdrawal(10); } } public void makeWithdrawal(int amount){ String str="asd" synchronized (str ) { if(account.getAmount()>10){ try{ Thread.sleep(5000); }catch(InterruptedException e){ e.printStackTrace(); } account.withdraw(amount); System.out.println(Thread.currentThread().getName()+" has withdrawn 10, current balance "+ account.getAmount()); }else{ System.out.println("Insufficient funds "+account.getAmount()); } } } }
Using a static synchronized block:
public class AccountOperations implements Runnable{ private static Account account = new Account(); public void run(){ for(int i=0;i<5;i++){ makeWithdrawal(10); } } public static void makeWithdrawal(int amount){ synchronized (String.class ) { if(account.getAmount()>10){ try{ Thread.sleep(5000); }catch(InterruptedException e){ e.printStackTrace(); } account.withdraw(amount); System.out.println(Thread.currentThread().getName()+" has withdrawn 10, current balance "+ account.getAmount()); }else{ System.out.println("Insufficient funds "+account.getAmount()); } } } }