commit
bf4fe52eb3
@ -0,0 +1,29 @@
|
||||
### IntelliJ IDEA ###
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
@ -0,0 +1,23 @@
|
||||
package singleton;
|
||||
|
||||
/*
|
||||
* 同1
|
||||
* */
|
||||
public class Singleton2 {
|
||||
private static final Singleton2 INSTANCE;
|
||||
static {
|
||||
INSTANCE = new Singleton2();
|
||||
}
|
||||
|
||||
private Singleton2() {
|
||||
}
|
||||
|
||||
public static Singleton2 getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Singleton2 singleton = Singleton2.getInstance();
|
||||
System.out.println(singleton);
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package singleton;
|
||||
|
||||
/*
|
||||
* 懒汉式 lazy loading
|
||||
* 虽然达到了按需初始化的目的, 同步代码块
|
||||
* */
|
||||
public class Singleton6 {
|
||||
private static Singleton6 INSTANCE;
|
||||
|
||||
private Singleton6() {
|
||||
}
|
||||
|
||||
public static synchronized Singleton6 getInstance() {
|
||||
synchronized (Singleton6.class){
|
||||
//双重检查
|
||||
if(INSTANCE == null) {
|
||||
INSTANCE = new Singleton6();
|
||||
}
|
||||
}
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Singleton6 singleton = Singleton6.getInstance();
|
||||
for (int i=0; i< 100; i++){
|
||||
new Thread(() -> System.out.println(singleton.hashCode())).start();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in new issue