同步的Getter和Setter

use*_*112 2 java concurrency getter-setter

我正在研究Java并发.我有一个关于synchronized和锁定的问题.

对于任何可变数据,我们应该将访问数据的所有方法放在同一个锁中.

但是,同样的锁是什么意思?

例:

public class SynchronizedInteger{
    private int value;
    public synchronized int get(){return value;}
    public synchronized void set(int value){this.value=value;}
}
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是为什么这两种方法都在同一个锁中?我知道他们是,但我想知道为什么?并且,这是否意味着类中的所有同步方法都在同一个锁中?

编辑:

所以,如果我在课程中再添加一个方法:

public synchronized void printOneToHunder(){

for(int i=0;i<100;i++) System.out.println(i);
Run Code Online (Sandbox Code Playgroud)

}

synchronized

public synchronized void printOneToHunder(){

public class SynchronizedInteger{
    private int value1;
    private int value2;
    public synchronized int get1(){return value1;}
    public synchronized void set1(int value){this.value1=value1;}
    public synchronized int get2(){return value2;}
    public synchronized void set2(int value){this.value2=value2;}       
}
Run Code Online (Sandbox Code Playgroud)

}

这个方法也会被包含在与setter和getter相同的块中?那么,当有一个线程使用setter或getter时,其他线程无法运行此方法?

而且,如果我将课程改为以下内容怎么办:

public class SynchronizedInteger{
    private int value;
    public synchronized int get(){return value;}
    public synchronized void set(int value){this.value=value;}
}
Run Code Online (Sandbox Code Playgroud)

根据我现在的理解,只有一个线程可以同时调用这些方法.那么是什么方法使一个线程可以修改value1而另一个线程来修改value2 ???

非常感谢您的善意澄清!!!!

Mat*_*Mat 5

您声明的所有非静态方法的synchronized行为基本上与代码一样:

public synchronized int get() {
  synchronized(this) {
    // the method code
  }
}
Run Code Online (Sandbox Code Playgroud)

即有一个隐含的锁定this.因此,所有非静态同步方法都将锁定调用它们的实例.

静态同步方法锁定类对象本身,而不是该类的实例.