マルチスレッドsynchronizedは正しい読み書きを保証します



package scjp;

public class Demo712 implements Runnable{

	private int a;
	private int b;
	
	public int read() {
			return a+b;
	}
	
	public void set(int a,int b){
		this.a=a;
		this.b=b;
	}
	
	@Override
	public void run() {
		for(int i=0;i<10;i++){
			this.set(i, i);
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(i + " " + this.read());
		}
	}
	
	public static void main(String[] args) {
		Demo712 demo712=new Demo712();
		Thread t1=new Thread(demo712);
		Thread t2=new Thread(demo712);
		t1.start();
		t2.start();
	}

}


出力:
0 0
0 2
1 2
1 4
2 4
2 6
3 6
3 8
4 8
4 10
5 10
5 12
6 12
6 14
7 14
7 16
8 16
8 18
9 18
9 18

1 4
2 6
明らかに非同期です.同期を追加する方法:
A.メソッドreadとsetにsynchronizedを付ける
public synchronized int read() {
			return a+b;
}
	
public synchronized void set(int a,int b){
		this.a=a;
		this.b=b;
}

B.ブロックにsynchronizedを付ける
public int read() {
           synchronized(this){ 
		return a+b;
           }
}
	
public synchronized void set(int a,int b){
           synchronized(this){
		this.a=a;
		this.b=b;
           }
}

この2つの方法はいずれも可能で、出力の結果は私は列挙しません.次に、エラーについて説明します.
public int read() {
           synchronized(a){ 
		return a+b;
           }
}
	
public synchronized void set(int a,int b){
           synchronized(b){
		this.a=a;
		this.b=b;
           }
}

このコードには2つの問題があります.第1 synchronizedのフォーマットはこのようなものです.

synchronized(object){
//synchronized block
}

a,bはint型変数、intはprimitive(int byte char boolean short long double float)であり、オブジェクトではないのでコンパイルはエラーを報告する.このコンパイルを通過させるにはa,bをIntegerまたは他のObjectのタイプとして明記しなければならない.
第二に、同期の変数はa、a、bのすべての同期出力が正しいことを必要とし、この問題を修正するには前の2つの方法しかない.前に見たsynchronizedも1つのObjectタイプのパラメータしか受け入れられないからだ.