public class Text02 {
public static void main(String[] args) {
// 單利:程序在運(yùn)行期間不管通過什么途徑,執(zhí)行創(chuàng)建一個對象,對象的生命周期是整個項(xiàng)目期間運(yùn)行
Person person = Person.getInstance();
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Student student = Student.getInstance();
System.out.println(student);
}
}).start();
}
}
}
// 方法一創(chuàng)建單利(一開始就有內(nèi)存)
class Person {//(在程序期間不能被釋放 所以加static 單利)
// static
static Person p = new Person();
static Person getInstance() {
return p;
}
}
// 第二種方法 (用的時候才會占用內(nèi)存)
class Student {
// volatile 每個線程都自己棧
volatile static Student stu = null;
static Student getInstance() {
synchronized (Student.class) {
if (stu == null) {
stu = new Student();
}
}
return stu;
}
}