package com.wz.thread.innerStatic;
/**
* 使用静态内置类来实现单例模式
* @author Administrator
*
*/
public class MyObject {
// 内部类的方式
private static class MyObjectHandler{
private static MyObject myObject = new MyObject();
}
private MyObject() {}
public static MyObject getInstance() {
return MyObjectHandler.myObject;
}
}
package com.wz.thread.innerStatic;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println(MyObject.getInstance().hashCode());
}
}
package com.wz.thread.innerStatic;
/**
* 输出的hascode值相同,说明是同一个对象
* @author Administrator
*
*/
public class Run {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
}