sychronized

3949 ワード

Javaは、synchronizedブロックという強制原子性の内蔵ロックメカニズムを提供します.1つのsynchronizedブロックには、ロックされたオブジェクトの参照(ロックされたオブジェクトとしてfinalである必要があり、ロックされたオブジェクトが再割り当てされないことを保証する)と、このロック保護されたコードブロックの2つの部分があります.
public class Example5 {
    
    final static Object lock = new Object();
    static int num = 0;
    
    public void add(){
        synchronized (lock) {
            num++;
        }            
    }
}

synchronizedメソッドは、メソッド全体を越えたsynchronizedブロックの簡単な説明であり、synchronizedメソッドのロックは、そのメソッドが存在するオブジェクト自体である.(静的synchronizedメソッドClassオブジェクトからロックを取得)
public class Example5 {
    
    static int num = 0;
    
    public synchronized void add(){
        num++;
    }
}

public class Example5 {

    static int num = 0;

    public void add(){
        synchronized (this) {
            num++;
        }
    }
}

 
静的sychronizedメソッド
public class Example5 {

    static int num = 0;

    public void opt1(){
        synchronized (Example5.class) {
            num++;
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            num--;
            System.out.println("  :"+Thread.currentThread().getId()+",num:"+num);
        }
    }
    
    //opt2 opt1    
    public static synchronized void opt2(){
        num++;
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        num--;
        System.out.println("  :"+Thread.currentThread().getId()+",num:"+num);
    }
    
    public static void main(String[] args){
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                Example5 example5 = new Example5();
                for (int i = 0; i < 100; i++) {
                    example5.opt1();
                }
            }
        }).start();
        
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    Example5.opt2();
                }
            }
        }).start();
    }
}