web.xml
<servlet>
<servlet-name>runthread</servlet-name>
<servlet-class>com.investoday.servlet.RunThread</servlet-class>
<load-on-startup>1</load-on-startup> <!--为1 表示服务启动就自动运行-->
</servlet>
<servlet-mapping>
<servlet-name>runthread</servlet-name>
<url-pattern>/runthread</url-pattern>
</servlet-mapping>
TimeThread.java --线程类
class TimeThread extends Thread
---------------------------------------------------------
public void run()
{
try
{
for(;;)//无限循环
{
// some thing to do
Thread.sleep(sleepTime);
}
} catch(Exception e)
{
e.printStackTrace();
}
}
----------------------------------------------------------------------------
RunThread.java --调用线程的类
---------------------------------------
package com.investoday.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class RunThread extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
try
{
TimeThread td = new TimeThread(1000);
td.start();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public void init(ServletConfig config) throws ServletException
{
TimeThread td = new TimeThread(10000);
System.out.println("to run thread.");
td.start();//执行 run 方法
}
}