package com.bjsxt.base.conn011; /** * The first way to write multi-threaded single column is the simplest. * @author Administrator * */ public class InnerSingleton { private static class Singletion { private static Singletion single = new Singletion(); } public static Singletion getInstance(){ return Singletion.single; } }
package com.bjsxt.base.conn011; /** * @author Administrator *The second way of writing multi-threaded single-column mode, two if judgments */ public class DubbleSingleton { private static DubbleSingleton ds; public static DubbleSingleton getDs(){ if(ds == null){ try { // Simulate the preparation time of the initialized object... Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace (); } synchronized (DubbleSingleton.class) { if(ds == null){ ds = new DubbleSingleton(); } } } return ds; } public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println(DubbleSingleton.getDs().hashCode()); } },"t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { System.out.println(DubbleSingleton.getDs().hashCode()); } },"t2"); Thread t3 = new Thread(new Runnable() { @Override public void run() { System.out.println(DubbleSingleton.getDs().hashCode()); } },"t3"); t1.start(); t2.start(); t3.start(); } }
package com.bjsxt.base.conn011; //Ordinary single-column mode multiple threads will create multiple objects public class Singleton { private static Singleton s = null; private void Singleton(){ } public static Singleton getS(){ if(s == null){ try { // Simulate the preparation time of the initialized object... Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace (); } s = new Singleton(); } return s; } public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println(Singleton.getS().hashCode()); } },"t1").start(); new Thread(new Runnable() { @Override public void run() { System.out.println(Singleton.getS().hashCode()); } },"t2").start(); new Thread(new Runnable() { @Override public void run() { System.out.println(Singleton.getS().hashCode()); } },"t3").start(); } }