单例
package singleton;
public class SingletonTest {
public static void main(String[] args) {
Thread thread1 = new Thread(new SingletonThread1());
Thread thread2 = new Thread(new SingletonThread2());
thread1.start();
thread2.start();
}
}
class Singleton{
private static Singleton singleton;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton == null){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
class SingletonThread1 implements Runnable{
@Override
public void run() {
System.out.println(Singleton.getInstance());
}
}
class SingletonThread2 implements Runnable{
@Override
public void run() {
System.out.println(Singleton.getInstance());
}
}