单例模式
单例模式可以让我们只创建一个对象从而避免了频繁创建对象导致的内存消耗和垃圾回收。
单利模式的优缺点和使用场景
应用场景
MySingleton01.java
/**
* 饿汉式
* @author 15062
*
*/
public class MySingleton01 {
private static MySingleton01 mySingleton01 = new MySingleton01();
private MySingleton01() {
}
public static MySingleton01 getInstance() {
return mySingleton01;
}
}
MyThread01.java
/**饿汉式
*
* @author 15062
*
*/
public class MyThread01 extends Thread {
@Override
public void run() {
System.out.println(MySingleton01.getInstance().hashCode());
}
public static void main(String[] args) {
MyThread01 t1 = new MyThread01();
MyThread01 t2 = new MyThread01();
MyThread01 t3 = new MyThread01();
t1.start();
t2.start();
t3.start();
}
}
MySingleton2.java
/**
* 懒汉式
* @author 15062
*
*/
public class MySingleton2 {
private static MySingleton2 mySingleton2;
private MySingleton2() {
}
// 设置同步方法效率太低了
synchronized public static MySingleton2 getInstance() {
try {
if (mySingleton2 != null) {
} else {
// 模拟在创建对象之前做一些准备性的工作
Thread.sleep(3000);
mySingleton2 = new MySingleton2();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return mySingleton2;
}
MyThread2.java
/**懒汉式
*
* @author 15062
*
*/
public class MyThread2 extends Thread {
@Override
public void run() {
System.out.println(MySingleton2.getInstance().hashCode());
}
public static void main(String[] args) {
MyThread2 t1 = new MyThread2();
MyThread2 t2 = new MyThread2();
MyThread2 t3 = new MyThread2();
t1.start();
t2.start();
t3.start();
}
}