init: 初始化,创建对象时
service: 服务核心方法,用来接收请求
destroy: 销毁对象
@Override
public void init(ServletConfig arg0) throws ServletException {
System.out.println("Servlet被创建了");
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
System.out.println("服务器收到请求了");
arg1.getWriter().write(new Date().toString());
}
@Override
public void destroy() {
System.out.println("Servlet被销毁了");
}
单例模式
–懒汉模式和恶汉模式
public class Singleton {
// 属性
int a;
// 方法
// 类加载时,对象就已经创建好 - 饿汉模式
// private static Singleton single = new Singleton();
// public static Singleton print() {
// return single;
// }
// 使用对象时,再创建对象 - 懒汉模式
private static Singleton single = null;
public static Singleton print() {
//锁住,不然线程执行到if语句归还时间片就会产生错误。
synchronized (single) {
if (single == null) {
single = new Singleton();
}
}
return single;
}
// 1.不能直接new,私有化构造器
private Singleton() {
}
}