java学习笔记之单例模式
单例模式
单例模式:见名思意就是一个类就只能创建一个实例,也就是只能创建一个对象
饿汉式单利模式:
1 //饿汉式 2 public class Student { 3 4 5 //1:构造方法私有 6 private Student(){} 7 //2:自己创建对象 8 private static Student stu = new Student(); 9 //3:创建一个方法,让别人可以获取该对象 10 public static Student getStudent(){ 11 return stu; 12 } 13 14 15 }
懒汉式单例模式:
1 //懒汉式 2 public class Worker { //类名.class 3 private Worker(){} 4 5 private static Worker worker = null;
//在静态同步方法中 锁对象就是 类名.class
6 public static synchronized Worker getWorker(){ 7 if(worker == null){ 8 try{Thread.sleep(50);}catch(Exception e){} 9 //T1 T2 T3 10 worker = new Worker(); 11 } 12 return worker; 13 } 14 }
不忘初心,方得始终