62,568
社区成员




package test;
// 线程安全的Singleton模式
class Singleton
{
private static Singleton sample;
private Singleton()
{
}
public static Singleton getInstance()
{
if (sample == null)
{
Thread.yield(); // 为了放大Singleton模式的线程不安全性
sample = new Singleton();
}
return sample;
}
}
public class MyThread extends Thread
{
public void run()
{
Singleton singleton = Singleton.getInstance();
System.out.println(singleton.hashCode());
}
public static void main(String[] args)
{
Thread threads[] = new Thread[5];
for (int i = 0; i < threads.length; i++)
threads[i] = new MyThread();
for (int i = 0; i < threads.length; i++)
threads[i].start();
}
}
public final class EagerSingleton
{
private static EagerSingleton singObj = null;
private EagerSingleton()
{
}
public static EagerSingleton getSingleInstance()
{
if (singObj == null) {
singObj = new EagerSingleton();
}
return singObj;
}
}