package dp
;
public class ThreadSingle {
private static ThreadSingle instance
;
private ThreadSingle(){}
public static ThreadSingle
getInstance() {
if (instance
== null
){
try{
Thread
.sleep(1);
}catch (InterruptedException e
){
e
.printStackTrace();
}
instance
= new ThreadSingle();
}
return instance
;
}
public static void main(String
[] args
) {
for (int i
=0;i
<100;i
++)
new Thread(() -> {
System
.out
.println(ThreadSingle
.getInstance().hashCode());
}).start();
}
}
实现单例最简单并且在高性能java一书中推荐使用枚举类。
public enum Single
{
INSTANCE
;
}
单例模式:核心思想一个类只有一个实例,获取示例时发现没有该实列就创建示例。
1.单例模式保证线程安全最简单的方式就是加synchronized 2.推荐使用枚举类 问题:枚举类是否线程安全?答案是肯定的