2012-02-22 52 views
0

我需要显示一些代码来解释我的问题。介入一个长时间运行的线程与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

顺便说一下,我不能使用睡眠/中断。

+0

“众多代码行”需要执行多长时间?一秒?一分钟?一小时 ? – Johannes 2012-02-22 13:44:39

+0

最多可能需要5或6分钟。 – GokcenG 2012-02-22 14:11:55

回答

1

没有这个线程的协作,没有干净的方法来阻止线程。所以,如果您需要尽快停止,您必须尽可能频繁地检查停止标志(在您的示例中为b)。

顺便说一句,b标志应该是volatile,否则你的线程可能永远不会停止。

+0

是的,你的关于易变点是正确的。如果你这么说线程生命周期,那么我需要在while循环中检查b很多次。 – GokcenG 2012-02-22 14:13:21

0

当上下文被破坏时,不要忘记加入线程。