public static void main(String[] args) throws InterruptedException {
//
//TaskManager tm = TaskManager.getInstance();
TaskManager tm = TaskManager.getInstance();
//TaskManager.m();
System.out.println(tm.getS());
System.out.println™;
System.out.println("休眠开始");
TimeUnit.SECONDS.sleep(10);//秒
System.out.println("休眠结束");
TaskManager tm1 = TaskManager.getInstance();
System.out.println(tm1.getS());
System.out.println(tm1);
}
}
//单例设计模式
//实现方式—饿汉式
//直接创建对象,没有线程安全问题
//只要类一加载对象就会创建,不管我们需不需要
class TaskManager{
private static Stack s = new Stack<>();
//私有化构造方法
private TaskManager(){
System.out.println(“栈内添加元素”);
s.push(“123”);
Timer timer = new Timer();
// 创建定时器任务
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
s.pop();
System.out.println(“栈内元素移除”);
}
};
timer.schedule(timerTask, 5000);
}
//本类创建对象
private static TaskManager tm = new TaskManager();
//提供静态方法
public static TaskManager getInstance(){
return tm;
}
public String getS(){
if (s.isEmpty()){
new TaskManager();
}
return s.peek();
}
}