澄清参数块同步的含义 [英] Clarification on the meaning of the parameter block synchronization

查看:53
本文介绍了澄清参数块同步的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这个表达式是否正确以及它是否意味着:我对字段状态设置了写锁定,然后我对其进行了更改.如果没有,我想知道参数的含义,因为我总是看到 this .

 公共类示例{私人int身份;公开示例(int状态){this.status =状态;}公共无效setStatus(int newStatus){已同步(this.status){this.status = newStatus;}}} 

解决方案

此代码有几处错误:

  1. 您不能在原始文件上进行同步.

    您可以将其更改为 Integer ,但请参见下文.

  2. 在非最终对象上同步不是一个好主意.

    您可以将其设置为最终

  3. 在同步化 时更改字段将以某些非常模糊的方式中断.现在是 final ,将是不允许的.

    在另一个字段上进行同步可能更好.

  4. 您还应该提供一种获取完整性的get方法.

所有这些问题已解决,您的代码如下所示:

 公共类示例{私有最终对象statusLock = new Object();私有整数状态;公共示例(整数状态){this.status =状态;}public void setStatus(Integer newStatus){已同步(statusLock){状态= newStatus;}}public Integer getStatus(){返回状态;}} 

现在-使用此代码-您问题的答案是种类.此处发生的是,您在更改值时通过任何其他线程通过设置方法锁定了全部 status 字段的访问权限.>

请注意,我没有在get方法中进行同步.如果我这样做了,那么上面的陈述就会改变.

i would like to know if this expression it is correct and if it means this: i put a write lock over the field status, and than i change it. If not, i would like to know what is the meaning of the paramenter, because i see always this.

public class Example {
    private int status;
    public Example(int status){
        this.status = status;
    }
    public void setStatus(int newStatus){
        synchronized(this.status){
            this.status = newStatus;
        }
     }
}

解决方案

There are several things wrong with this code:

  1. You cannot synchronize on a primitive.

    You could change it to an Integer but see below.

  2. Synchronizing on a non-final object is not a good idea.

    You could make it final

  3. Changing a field while it is being synchronized on is going to break in some very obscure ways. And now it is final it will not be allowed.

    Probably better to synchronize on another field.

  4. You should also provide a get method for completeness.

With all of these issue fixed your code looks something like this:

public class Example {
  private final Object statusLock = new Object();
  private Integer status;

  public Example(Integer status) {
    this.status = status;
  }

  public void setStatus(Integer newStatus) {
    synchronized (statusLock) {
      status = newStatus;
    }
  }


  public Integer getStatus() {
    return status;
  }
}

Now - with this code - the answer to your question is kind of. What happens here is that you lock all access to the status field through the set method from any other thread while you change it's value.

Notice that I do not synchronise in the get method. If I did then the above statement would change.

这篇关于澄清参数块同步的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆