栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用于异步处理的tomcat 6线程池

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用于异步处理的tomcat 6线程池

回答您的简短问题:

在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
方法感兴趣。

有关

Executors
JVM中的更多常规信息,您可能需要阅读以下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的引用,并可以从其他线程中查询它,以了解它是否已完成以及结果如何。

希望这可以帮助…



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/447380.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号