1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package designpatterns;
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
}
public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }
public static void main(String[] args) { MyThread[] threads = new MyThread[5]; for (int i = 0; i < 5; i++) { threads[i] = new MyThread(String.format("Thread-%d", i + 1)); threads[i].start(); } } }
class MyThread extends Thread { String name;
public MyThread(String name) { this.name = name; }
@Override public void run() { Singleton instance = Singleton.getInstance(); System.out.println(this.name + ":" + instance.hashCode()); } }
|