注意:对于方法一、方法二,都要写一个私有的构造方法,因为如果省略这一步的话,外界就可以通过new,调用它的默认的公有不带参数构造方法了。
区别如下
1、对于方法一:
(1)不使用的时候不生成单例
(2)多线程的情况下,有可能出现并不是单例的情况。
package com.test2;
public class Singleton
{
private static Singleton singleton;
private Singleton()
{
}
public static Singleton getInstance()
{
if(null == singleton)
{
/* try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
} */
singleton = new Singleton();
}
System.out.println(singleton);
return singleton;
}
}
针对于方法1的测试类(测试时恢复上面单例模式的注解部分)
package com.test2;
public class SingletonTest
{
public static void main(String[] args)
{
for(int i = 0 ; i < 10 ; ++i)
{
MyThread myThread = new MyThread();
myThread.start();
}
}
}
class MyThread extends Thread
{
@Override
public void run()
{
Singleton.getInstance();
}
}
2、方法二(推荐)
(1)类加载时就生成单例。
(2)多线程时也始终是单例模式。
package com.test2;
public class Singleton2
{
private static Singleton2 singleton = new Singleton2();
private Singleton2()
{
}
public static Singleton2 getInstance()
{
/* try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(singleton); */
return singleton;
}
}
针对于方法2的测试类(测试时恢复上面单例模式的注解部分)
package com.test2;
public class Singleton2Test
{
public static void main(String[] args)
{
for(int i = 0 ; i < 10 ; ++i)
{
MyThread2 myThread2 = new MyThread2();
myThread2.start();
}
}
}
class MyThread2 extends Thread
{
@Override
public void run()
{
Singleton2.getInstance();
}
}