单例模式---> 懒汉式
public class Student {
private static Student instance = null;
private Student() {}
对象相同
private static Student getInstance(){
//如果第一个线程过来发现Student对象为null,则进入同步方法
//如果第二个线程过来发现对象已经存在则不会在进入同步方法,而是直接获取已经存在的对象
if(instance == null){
synchronized (Student.class) {
if(instance == null){
instance = new Student();
}
}
}
return instance;
}
private static synchronized Student getInstance2(){
if(instance == null){
instance = new Student();
}
return instance;
}
private static Student getInstance3(){
synchronized (Student.class) {
if(instance == null){
instance = new Student();
}
}
return instance;
}
private static Student getInstance4(){
if (instance == null){
instance = new Student();
}
return instance;
}
static class SyncStudent extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"---->" + Student.getInstance4());
}
}
public static void main(String[] args) {
SyncStudent syncStudent1 = new SyncStudent();
SyncStudent syncStudent2 = new SyncStudent();
syncStudent1.start();
syncStudent2.start();
}
}