我需要显示一些代码来解释我的问题。介入一个长时间运行的线程与contextDestroyed
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ServletContextAttribListener implements ServletContextListener
{
private ServletContext context = null;
private MyThread myThread = new MyThread(true);
// This method is invoked when the Web Application
// is ready to service requests
public void contextInitialized(ServletContextEvent event)
{
this.context = event.getServletContext();
// Output a simple message to the server's console
myThread.start();
System.out.println("The Simple Web App. Is Ready");
}
public void contextDestroyed(ServletContextEvent event)
{
// Output a simple message to the server's console
System.out.println("The Simple Web App. Has Been Removed");
myThread.setB(false);
this.context = null;
}
public class MyThread extends Thread
{
private boolean b;
public MyThread(boolean b)
{
this.b = b;
}
@Override
public void run()
{
int i = 0;
int j = 0;
while (b)
{
//This part is important
for (i = 0; i < 1000000; i++)
{
}
//
j++;
}
System.out.println("Thread stopped i:->" + i + " j:->" + j);
}
public boolean isB()
{
return b;
}
public void setB(boolean b)
{
this.b = b;
}
}
}
正如你可以看到它是非常小的虚拟程序。我没有写web.xml,我只是使用listener-class。 当我部署战争,启动和停止Tomcat,该程序的输出是:
The Simple Web App. Is Ready
The Simple Web App. Has Been Removed
Thread stopped i:->1000000 j:->17296
正如你可以看到我1000000在for循环。我想要的是打破循环,无论我是1000000还是小于这个。
你可以说,我可以用b条件与在for循环我<百万但在我实际的程序我没有这样的for循环。我只是有一个像这里一样的while循环,但内部有许多代码行。我不想在每次内部检查b。
顺便说一下,我不能使用睡眠/中断。
“众多代码行”需要执行多长时间?一秒?一分钟?一小时 ? – Johannes 2012-02-22 13:44:39
最多可能需要5或6分钟。 – GokcenG 2012-02-22 14:11:55