欢迎光临散文网 会员登陆 & 注册

ElasticStack高级开发与架构2023\/--》ccys1473

2023-06-29 11:48 作者:ws7474ni尐  | 我要投稿

以下内容忽略

4、static + private + getInstance + instance + synchronized(对象锁)缩小锁代码,但不安全

package Sigleton; public class T04 {    private static T04 t04;    public static T04 getInstance(){        if(t04 == null){            synchronized (T04.class){                try {                    Thread.sleep(2);                }catch (Exception e){                }                t04 = new T04();            }        }        return t04;    }    public static void main(String[] args){        for(int i=0;i<20;i++){            new Thread(new Runnable() {                @Override                public void run() {                    System.out.println(T04.getInstance().hashCode());                }            }).start();        }    } }


ElasticStack高级开发与架构2023\/--》ccys1473的评论 (共 条)

分享到微博请遵守国家法律