@Test publicvoidtestSingleton()throws InterruptedException { long start=System.currentTimeMillis(); List<Thread> threadList = new ArrayList<>(); for (int i = 0; i < 1000; i++) { Thread thread = new Thread(() -> { Singleton.getInstance(); }); threadList.add(thread); thread.start(); } for (Thread t : threadList) { t.join(); } long end=System.currentTimeMillis(); System.out.println("运行耗时:"+(end-start)); }
方案一:使用synchronized 关键字
1 2 3 4 5 6 7 8 9 10
publicstatic Singleton getInstance(){ synchronized (Singleton.class){ if (singleton == null) { System.out.println("创建对象"); singleton = new Singleton(); } } return singleton; }