标签:
1、spring
配置init-method方法
例子如下
spring-xml------------------------------------------------
<context:annotation-config/>
<bean id="dataProcessor" class="com.thread.DataProcessor" scope="singleton" init-method="start" destroy-method="cleanUp"/>
java---------------------------------------------
package com.thread;
import java.util.HashMap;
import java.util.Map;
public class DataProcessor {
private static DataProcessor dataProcessor=null;
private DataProcessor(){}
public static DataProcessor getInstance(){
if(dataProcessor==null){
dataProcessor=new DataProcessor();
}
return dataProcessor;
}
/**数据转存线程数*/
private static int DATA_HANDLER_NUM = 4;
/**线程状态存储*/
public static Map<String, Boolean> threadStatusMap = new HashMap<String, Boolean>();
public void start(){
String name;
for(int i = 0 ; i < DATA_HANDLER_NUM; i++){
name = "dataHandlerRunnerThread " + i;
threadStatusMap.put(name, true);
new Thread(new DataHandlerRunner(threadStatusMap), name).start();
}
}
public void cleanUp(){
System.out.println("cleanUp");
}
}
2、servlet
web.xml ------------------------------------------
<listener>
<listener-class>com.listener.MyServletContextListener</listener-class>
</listener>
Java 添加监听器------------------------------------
package com.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.thread.DataProcessor;
/**
* Application Lifecycle Listener implementation class MyServletContextListener
*
*/
public class MyServletContextListener implements ServletContextListener {
/**
* Default constructor.
*/
public MyServletContextListener() {
System.out.println("MyServletContextListener()");
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent arg0) {
DataProcessor d=DataProcessor.getInstance();
d.start();
System.out.println(arg0.toString());
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("contextDestroyed()");
}
}
标签:
原文地址:http://www.cnblogs.com/lanliying/p/5453951.html