丰乐

synchronized关键字

synchronized关键字

1 应用

  1. 对方法加锁
  2. 对代码块加锁
  3. 对class对象加锁
  4. 对内部对象加锁
public class Counter {
    private int count;

    public synchronized void inrc(){
        ++count;
    }
    public synchronized int getCount() {
        return count;
    }

}

public class Counter2 {
    private int count;

    public  void inrc(){
        synchronized(this) {
            ++count;
        }
    }
    public int getCount() {
        synchronized(this) {
            return count;
        }
    }

}

public class Counter3 {
    private static int count = 0;

    public static void inrc(){
        synchronized(Counter3.class) {
            ++count;
        }
    }
    public static int getCount() {
        synchronized(Counter3.class) {
            return count;
        }
    }

}

public class Counter4 {
    private int count;

    private Object lock = new Object();

    public  void inrc(){
        synchronized(lock) {
            ++count;
        }
    }
    public int getCount() {
        synchronized(lock) {
            return count;
        }
    }

}

2 更进一步

可重入性:同一个线程获取锁后,调用其他需要锁的方法,可以直接使用

内存可见性:锁释放时所有写入都会写入内存

死锁:同时含有锁的情况

  • a锁定lock1需要lock2
  • b锁定lock2需要lock1

3 原理

对象头的mark workd(64位)8字节。锁标志位和占用的内存

posted on 2021-10-05 17:39  李蝉儿  阅读(21)  评论(0编辑  收藏  举报

导航