回答你的简短问题:
在 JVM 中,线程池被抽象在java.util.concurrent.ExecutorService
接口后面。这个接口有不同的实现,但在大多数情况下,这个接口的方法就足够了。
要创建特定的线程池,请查看java.util.concurrent.Executors
类:
http ://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html
,其中包含用于创建不同ExecutorService
接口实现的静态工厂方法. 您可能对newFixedThreadPool(int threadsNumber)
方法感兴趣newCachedThreadPool
。
有关Executors
JVM 的更多一般信息,您可能需要阅读以下 Oracle 教程:http ://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html
因此,要在 Tomcat 下使用线程池 ( ExecutorService
),您应该执行以下操作:
.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)
@Override
public 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 code 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
从 webapp 获得对几乎任何地方的引用):
Callable<ResultOfMyTask> callable = new Callable<ResultOfMyTask>() {
public ResultOfMyTask call() {
// here goes your task code 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 的引用,并可以从其他线程查询它以了解它是否已完成以及结果是什么。
希望这可以帮助...