虚拟机必须保证()方法在多线程环境下被同步加锁。(并且初始化一次)

虚拟机必须保证()方法在多线程环境下被同步加锁。(并且初始化一次)

package com.coderman;

/**
 * @Author zhangyukang
 * @Date 2020/4/7 20:02
 * @Version 1.0
 **/
public class Demo2 {
    public static void main(String[] args) {
        Runnable runnable=()->{
            System.out.println("线程:"+Thread.currentThread().getName()+"start");
            A a = new A();
            System.out.println("线程:"+Thread.currentThread().getName()+"end");
        };
        new Thread(runnable).start();
        new Thread(runnable).start();
    }
}
class A{
    static {
        if(true){
            System.out.println(Thread.currentThread().getName()+"初始化当前类");
            while (true){}
        }
    }
}

出现线程阻塞

线程:Thread-0start
线程:Thread-1start
Thread-0初始化当前类

如果我们将类初始化里的死循环去掉的话,那么结果如下,可以看到只初始化一次

线程:Thread-1start
线程:Thread-0start
Thread-1初始化当前类
线程:Thread-1end
线程:Thread-0end

应用:我们可以利用这一特性写一个线程安全的单例


class SingleDemo{

    private static SingleDemo instance=new SingleDemo();

    private SingleDemo(){}
    
    public static SingleDemo getInstance(){
        return instance;
    }
}
# JVM  

评论

公众号:mumuser

企鹅群:932154986

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×