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字节。锁标志位和占用的内存

  • 相关阅读:
    python -- 面向对象
    python应用----函数
    python
    python 基础应用5-简单购物车
    python 基础知识5-集合
    python 基础应用4
    python 基础知识4
    python 基础知识3-列表元祖
    python 基础应用3
    无法进入局域网远程桌面--Windows防火墙设置
  • 原文地址:https://www.cnblogs.com/beckbi/p/15369109.html
Copyright © 2011-2022 走看看