class Singleton {
private Singleton() {
}
private static Singleton singleton;
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
public class SingletonTest extends Thread{
private Singleton s;
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread.currentThread().setPriority(MIN_PRIORITY);
SingletonTest s1=new SingletonTest();
SingletonTest s2=new SingletonTest();
s1.setPriority(MAX_PRIORITY);
s2.setPriority(MAX_PRIORITY);
System.out.println(s1.getSingleton()==s2.getSingleton());
/*
* 为了使主线程的打印语句在s1,s2执行run方法之后,我设定了线程执行的优先级。
* 打印结果为true
*/
}
@Override
public void run() {
// TODO Auto-generated method stub
s = Singleton.getInstance();
}
public Singleton getSingleton() {
return s;
}
}
|