Recent projects have such a need: The original system has a function of calculation, but the function of the execution time will be very long (probably need a few hours to complete), if the implementation of the error in the process, can only silently wait for the wrong execution to complete the line, can not be dynamic to the function to stop.
after I learned the project requirements, I wrote the following small example:
Package com.iamzken.test;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
The public class Test extends HttpServlet {//This thread represents the thread that executes the task private volatile thread t; @Override protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException
{DoPost (req, resp); @Override protected void DoPost (final httpservletrequest req, final HttpServletResponse resp) throws Servletexcep
tion, IOException {//switch parameter switch, value on means to start thread t to perform the appropriate task, and the value of off represents the thread t String s = req.getparameter ("switch") to stop executing the task;
if ("Off". Equals (s)) {t.stop (); }else if ("on". Equals (s)) {t = new Thread (new Runnable () {//run's method body represents the task to be performed @Override public void run (
) {Req.setattribute ("name", Req.getparameter ("flag"));
int i = 0; while (I < 10000000) {System.out.println (++i);
}
}
});
Start thread T.start ();
The main thread can continue t.join () after execution of a try {///T).
SYSTEM.OUT.PRINTLN (req);
Req.getrequestdispatcher ("/my001.jsp"). Forward (req, resp);
catch (Exception e) {e.printstacktrace ();
}
}
}
The above is the main servlet code:
access path is: Http://localhost:8080/web001/test.do?flag=xxyyzz&switch=off There are two types of switch switch parameters: On and off,on represent the tasks that are performed by the thread, and off to represent the tasks being performed by the threads in the interrupt.
finally attach the complete project source code.
Web001.rar