tomcat 启动初始化一个线程

web.xml:



com.fk.MyServletContentListener



listener:


public class MyServletContentListener implements ServletContextListener {

ServerThread st = null;

public void contextInitialized(ServletContextEvent sce) {
// 重写的contextInitialized方法
sce.getServletContext().log("[fiker.Server] Start ServerThread.");

st = new ServerThread();
st.start();

sce.getServletContext().log("[fiker.Server] ServerThread starting succ...");
}

public void contextDestroyed(ServletContextEvent sce) {
// 重写的contextDestroyed方法
sce.getServletContext().log("[fiker.Server] Stop ServerThread.");

st.setFlag(false);

sce.getServletContext().log("[fiker.Server] ServerThread stop succ...");
}


}


serverThread:
public class ServerThread extends Thread {
private boolean flag=true;
ServerSocket ss;
public void run(){
try {
ss=new ServerSocket(9999);
} catch (IOException e) {
// TODO Auto-generated catch block
this.setFlag(false);
e.printStackTrace();
}
Socket s;
while(flag)
{
try {
s=ss.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
this.setFlag(false);
e.printStackTrace();
}
}

}
public void setFlag(boolean flag) {
this.flag = flag;
}

}

你可能感兴趣的:(胡言乱语,jsp)