25

我知道

当您同步一段代码时,您指定要使用哪个对象的锁作为锁,例如,您可以使用一些第三方对象作为这段代码的锁。这使您能够在单个对象中拥有多个用于代码同步的锁。

但是,我不明白需要将参数传递给块。因为我是否将字符串的实例传递给同步块并不重要,因为同步块可以完美地工作,而与传递给块的参数无关。

所以我的问题是,无论如何,同步块是否会阻止两个线程同时进入临界区。那么为什么需要传递参数。(我的意思是默认获取某个随机对象的锁定)。

我希望我正确地提出了我的问题。

我已经尝试了以下示例,其中随机参数是同步块。

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());
            }
        }

    }

}
4

3 回答 3

38

因为我是否将字符串的实例传递给同步块并不重要,因为同步块可以完美地工作,而与传递给块的参数无关。

参数的目的有两个:

  1. 它使同步同一对象上的其他块成为可能,因此如果您有两个可能更改同一对象状态的代码块,它们不会相互干扰。

    例如:

    public void getSum() {
        int sum = 0;
        synchronized (this.list) {
            for (Thingy t : this.list) {
                sum += t.getValue();
            }
        }
        return sum;
    }
    
    public void addValue(int value) {
        synchronized (this.list) {
            this.list.add(new Thingy(value));
        }
    }
    

    在那里,重要的是我们同步跨线程的两个访问。list当另一个线程正在调用时,我们不能addValue在列表上调用和跺脚getSum

  2. 它可以确保您以正确的粒度进行同步。如果您正在序列化对特定于实例的资源的访问,那么跨实例这样做是没有意义的;如果它们在不同的实例上运行,您应该允许多个线程进入块。这就是为什么您会在this(或更通常是 的某个字段this)上同步特定于实例的资源,或者如果它是静态资源,则在类(或更通常是某个类字段)上进行同步。同样,this如果您只需要保护它的特定字段,则无需同步。

    例如:

    // (In MyClass)
    
    public void getThingySum() {
        int sum = 0;
        synchronized (this.thingyList) {
            for (Thingy t : this.thingyList) {
                sum += t.getValue();
            }
        }
        return sum;
    }
    
    public void addThingy(Thingy t) {
        synchronized (this.thingyList) {
            this.thingyList.add(t);
        }
    }
    
    public void getNiftySum() {
        int sum = 0;
        synchronized (this.niftyList) {
            for (Nifty n : this.niftyList) {
                sum += n.getValue();
            }
        }
        return sum;
    }
    
    public void addNifty(Nifty n) {
        synchronized (this.niftyList) {
            this.niftyList.add(t);
        }
    }
    

    在那里,我们同步访问this.thingyListon this.thingyList, notthisMyClass.class。如果一个线程正在调用getThingySum而另一个线程正在调用,那很好addNifty,因此同步this将是矫枉过正的。


重新你的str例子:

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());
        }
    }

}

那里的注释不正确,任何非null实例都不能充分保护该代码。以上似乎工作的原因是字符串实习:所有线程都使用相同的String实例,因为字符串文字会自动放入字符串intern池中。(这意味着您过度同步;它是 JVM 范围的,而不是特定于实例的。)所以它有效,但不是因为它只是任何对象。如果您将其更改为:

String str = "asd";

Object o = new Object();

并对此进行同步,它不会对帐户的序列化访问做任何事情。

在您的示例中,要同步的正确方法是this.account.

于 2015-04-26T10:51:07.653 回答
9

如果无论如何,同步块会阻止两个线程同时进入临界区。那么为什么需要传递参数呢?

同步块根据您传递给它的对象决定停止哪些线程。您传递的对象用作由同步块保护的监视器部分的标识符。

您的程序中可能有许多监视器部分,所有这些部分都可以彼此同时执行。例如,如果您有两个必须同时访问的不相关的集合,您可以为每个集合设置单独的监视器部分。这种方式只有在其他线程已经在访问同一个集合时才会停止线程;访问两个不同集合的两个不同线程将被允许同时进行。

你的第一个例子很重要。它起作用的原因是字符串对象被初始化为字符串文字。由于literal的interning,所有进入函数的线程都会获得相同的String对象,所以synchronized块会适当的保护monitor部分。

于 2015-04-26T10:51:44.390 回答
0

此外,您可能需要将实例 X 的对象传递给同步的参数,以防您需要将其传递给等待队列(通过使用 X.wait())。然后,您可以从另一个线程通过在 X 上调用 notify() 来通知对象(在需要时)。

于 2021-12-20T16:26:28.227 回答