回答您的简短问题:
在JVM中,线程池是在
java.util.concurrent.ExecutorService接口后面抽象的。该接口有不同的实现,但是在大多数情况下,该接口的方法就足够了。
要创建特定的线程池,请看一下
java.util.concurrent.Executors类:http
:
//docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html
,其中包含用于创建
ExecutorService接口的不同实现的静态工厂方法。。您可能对
newFixedThreadPool(intthreadsNumber)和
newCachedThreadPool方法感兴趣。
有关
ExecutorsJVM中的更多常规信息,您可能需要阅读以下Oracle教程:http
:
//docs.oracle.com/javase/tutorial/essential/concurrency/executors.html
因此,要
ExecutorService在Tomcat下使用线程池(),您应该执行以下操作:
.1。如果尚未完成,请在接口
web.xml实例中创建并注册该
javax.servlet.ServletContextListener接口(这将充当您的Web应用程序的入口点)。
.2。在
contextInitialized(ServletContextEvent)方法中,您创建
ExecutorService(线程池)的实例并将其存储在
ServletContext属性映射中,以便可以从您的webapp中的任何点访问它,例如:
// following method is invoked one time, when you web application starts (is deployed)@Overridepublic void contextInitialized(ServletContextEvent servletContextEvent) { // ... final int numberOfThreads = ...; final ExecutorService threadPool = Executors.newFixedThreadPool(numberOfThreads); // starts thread pool final ServletContext servletContext = servletContextEvent.getServletContext(); servletContext.setAttribute("threadPoolAlias", threadPool); // ...}// following method is invoked one time when your web application stops (is undeployed)public void contextDestroyed(ServletContextEvent servletContextEvent) { // following pre is just to free resources occupied by thread pool when web application is undeployed final ExecutorService threadPool = (ExecutorService) servletContextEvent.getServletContext().getAttribute("threadPoolAlias"); threadPool.shutdown();}.3。某处在
Servlet.service方法或任何地方你的webapp(你应该能够获得以基准
ServletContext从Web应用程序几乎任何地方):
Callable<ResultOfMyTask> callable = new Callable<ResultOfMyTask>() { public ResultOfMyTask call() { // here goes your task pre which is to be invoked by thread pool }};final ServletContext servletContext = ...;final ExecutorService threadPool = (ExecutorService) servletContext.getAttribute("threadPoolAlias");final Future<ResultOfMyTask> myTask = threadPool.submit(callable);;您应该存储对myTask的引用,并可以从其他线程中查询它,以了解它是否已完成以及结果如何。
希望这可以帮助…



