内存模型

1.4 Java的 内存模型

是否线程安全
线程安全与cpu资源的抢夺
多线程在读写共享变量时引发的问题

线程的原子性

多个变量访问同一个变量的时候就会出现''线程安全的问题”。

Sychonize 关键字的使用

线程间等待唤醒机制

1.5 生产者消费者模型

1.6 Locker各种锁

CAS AQS

单列模式与多线程

  • 饿汉式
    懒汉式是指在类初始的已经将对象加载完毕,最简单的实现办法就直接new一个对象,就像一个饥饿的汉子。

    public class Singleton{  
        private Singleton(){};
        private static Singleton single = new Singleton();
        public static Singleton getInstance(){
          return single;
        }      
    };
    
  • 懒汉式

    public class Singleton{     
       private static Singleton singleton;
       private Singleton(){}
       public static Singleton getInstance(){
         if(singleton == null){
          singleton = new Singleton();
         }
        return singleton;}
    }
    

这种饿汉式的写法在单线程环境下,初看起来是没有问题。但是如果在多线程的环境下就回出现错误。
简单直接的解决方案就是给 getInstance 方法加锁。

  • 方法锁

    private static Singleton singleton;
       private Singleton(){}
    
       public synchronized static Singleton getInstance(){
        if(singleton == null){
         singleton = new Singleton();
        }
       return singleton;}
     }
    
  • 代码块加锁

    public class Singleton{
        private static Singleton singleton;
        private Singleton(){}
        public  static Singleton getInstance(){
        synchronized (Singleton.class){
         if(singleton == null){
             singleton = new Singleton();
           }
         }
         return singleton;
       }
    }
    
  • 只针对某些重要步骤加锁

    public class Singleton {
      private static Singleton singleton;
      private Singleton(){}
      public  static Singleton getInstance(){
        if(singleton == null){
           synchronized (Singleton.class){
           singleton = new Singleton();
           }
        }
       return singleton;
       }
     }
    
  • 使用DCL 双检查机制来实现多线程下的延迟加载

    public class Singleton {
      private static Singleton singleton;
      private Singleton(){}
      public  static Singleton getInstance(){
        if(singleton == null){
           synchronized (Singleton.class){
           singleton = new Singleton();
           }
        }
       return singleton;
       }
     }
    
  • 静态内置类来实现单例模式

  • 序列和反序列化实现单例模式

  • static静态快实现单例模式

public class Singleton {
private Singleton(){    
}
private static  Singleton singleton = null;

 static {
     singleton = new Singleton();}
 public Singleton getSingleton(){
    return  singleton;
}}
  • emnu实现单例模式

JVM 层级.


image.png

as-if-serial
不管硬件什么顺序,单线程执行的结果不变,看上去像是 serial

ZGC 的 NUMA Aware
Non Uniform Memory Access,
分配内存会优先分配该线程所在的CPU的最近内存

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容