将参数传递给同步块的目的是什么?
我知道那件事
同步代码块时,可以指定要用作锁的对象锁,以便例如,可以使用某些第三方对象作为此段代码的锁。这使您能够在单个对象中具有多个用于代码同步的锁。
但是,我不明白是否需要将参数传递给块。因为我是否将 String 的实例传递给同步块并不重要,所以无论传递给块的参数如何,同步块都可以完美地工作。
所以我的问题是,如果无论如何同步块阻止两个线程同时进入关键部分。那么为什么需要传递一个参数。(我的意思是默认在一些随机对象上获取锁定)。
我希望我正确地构建了我的问题。
我已经尝试了以下示例,其中随机参数是同步块。
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();
    }
}
使用非静态同步块:
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 /* pass any non-null object the synchronized block works*/) {
            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());
            }
        }
    }
}
使用静态同步块:
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 /* pass any class literal synchronized block works*/) {
            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());
            }
        }
    }
}