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

  • 相关阅读:
    使用PWS调试cgi,php
    解决联想电脑常见故障及内存不足的几种方法
    How Many Tables (并查集)
    Prim
    小希的迷宫(并查集)
    并查集
    Is It A Tree?(并查集)
    hdu 1003 Max Sum(最大子窜和)
    More is better(并查集)
    01背包精讲
  • 原文地址:https://www.cnblogs.com/beckbi/p/15369109.html
Copyright © 2011-2022 走看看