zoukankan      html  css  js  c++  java
  • 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字节。锁标志位和占用的内存

  • 相关阅读:
    HDU 1251 统计难题 字符匹配
    mac 安装mysql
    ubuntu git 下添加 ssh
    mac下virtualenv使用
    git-ssh配置和使用
    在PythonAnyWhere上部署Django项目
    ImportError: No module named PIL
    mysql 命令行操作
    ubuntu安装ssh
    常用git命令
  • 原文地址:https://www.cnblogs.com/beckbi/p/15369109.html
Copyright © 2011-2022 走看看