java面试单例模式相关
2018-04-09 本文已影响0人
pr0metheus
面试题目一:请写出多种单例模式,并说出他们的区别
答案:具体代码如下
//单例模式-饿汉式
public class Singleton {
public static Singleton singleton = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return singleton;
}
}
//单例模式-懒汉式
public class Singleton2 {
public static Singleton2 singleton2;
private Singleton2() {
}
public static Singleton2 getInstance() {
if (singleton2 == null) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
singleton2 = new Singleton2();
}
return singleton2;
}
}
//饿汉式单例模式测试代码
public class SingletonTest {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new MyThread().start();
}
}
}
class MyThread extends Thread {
@Override
public void run() {
Singleton instance = Singleton.getInstance();
System.out.println(instance);
}
}
//懒汉式单例模式测试代码
public class SingletonTest2 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new MyThread2().start();
}
}
}
class MyThread2 extends Thread {
@Override
public void run() {
Singleton2 instance = Singleton2.getInstance();
System.out.println(instance);
}
}
总结:上述两种单例模式在单线程的情况下都符合单例的要求,但是懒汉式单例模式在多线程的情况下会出现多例的情况,不符合单例模式的要求,而饿汉式单例模式在多线程的情况下仍只会产生一个实例,符合单例模式的要求。故如果在多线程环境下想要使用单例模式那么应用饿汉式单例模式