资讯动态

单例模式并使用多线程方式验证

发布时间:2026/8/20 19:14:01 来源:尧图企业网站定制
题目编写单例模式并使用多线程方式验证代码示例public class DanLi { public static void main(String[] args) throws Exception { /** * Java不允许在lambda中修改栈上的局部变量 * danli数组,数组变量是在栈上面的,数组实例是在堆中 * 所以不能修改danli数组变量,可以修改在堆中数组实例中的数据 */ Single[] singles new Single[2]; Thread thread1 new Thread(() - { singles[0] Single.getInstance(); }); Thread thread2 new Thread(() - { singles[1] Single.getInstance(); }); thread1.start(); thread2.start(); //确保thread1线程和thread2线程在主线程之前执行,确保实例创建 thread1.join(); thread2.join(); System.out.println(singles[1] singles[0]); } } class Single { private static volatile Single single new Single(); private Single(){ } public static Single getInstance(){ if(single null){ synchronized (Single.class){ if(single null){ single new Single(); } } } return single; } }

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价