/**
* 线程安全的单例模式:
*
*/
package yxxy.c_023;
import java.util.Arrays;
public class Singleton {
//无参
private Singleton() {
System.out.println("single");
}
private static class Inner {
private static Singleton s = new Singleton();
}
public static Singleton getSingle() {
return Inner.s;
}
//有参
/**
* private static class Inner {
* private static Singleton getInstance (String s,int i) {
* return new Singleton(s, i);
* }
* }
*
* public static Singleton getSingle(String s,int i) {
* return Inner.getInstance(s, i);
* }
*
*/
public static void main(String[] args) {
Thread[] ths = new Thread[200];
for(int i=0; i<ths.length; i++) {
ths[i] = new Thread(()->{
Singleton.getSingle();
});
}
Arrays.asList(ths).forEach(o->o.start());
}
}
可以用到实例化对象和固定值计算