java 创建一个工作线程并从 servlet 或 Spring 控制器运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7203042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:03:41  来源:igfitidea点击:

Create a worker thread and run from a servlet or Spring controller

javamultithreadingspringservletsthreadpool

提问by gigadot

I would like to execute some task after a user request in background. My initial idea is to create a work thread and execute it from a servlet. However, I do not want too many threads to be running at the same time so I will need something like a thread pool.

我想在后台用户请求后执行一些任务。我最初的想法是创建一个工作线程并从 servlet 执行它。但是,我不希望同时运行太多线程,因此我需要诸如线程池之类的东西。

Since I am already using Spring with my web application, I am wondering if there is anything in Spring or other libraries I can use to handle this problem without having to implement my own codes.

由于我已经在我的 Web 应用程序中使用 Spring,我想知道 Spring 或其他库中是否有任何东西可以用来处理这个问题,而无需实现我自己的代码。

采纳答案by alvi

creating your own threads is often not advisable within a container as this can screw up thread pooling, i.e. the container unexpectantly runs out of threads. There is good quartz support in spring which may do exactly what you need, e.g. you can configure that the background job runs synchronously or asynchronously.

在容器中创建自己的线程通常是不可取的,因为这可能会破坏线程池,即容器意外地用完了线程。spring 中有很好的石英支持,它可以完全满足您的需求,例如,您可以配置后台作业同步或异步运行。

回答by atrain

Use @Asyncto spawn asynchronous threads; Spring can manage those, like every other service it provides. Example blog post: http://blog.springsource.com/2010/01/05/task-scheduling-simplifications-in-spring-3-0/

@Async产卵异步线程; Spring 可以管理这些,就像它提供的所有其他服务一样。示例博客文章:http: //blog.springsource.com/2010/01/05/task-scheduling-simplifications-in-spring-3-0/

回答by Srikanth Venkatesh

Quartz API can be used for your task.

Quartz API 可用于您的任务。

Check this example Integrating Quartz in a J2EE application

检查此示例在 J2EE 应用程序中集成 Quartz

回答by Eelke

Manually creating threads doesn't allways work well in a Java EE environment (and sometimes is prohibited by the container). Creating a background task in Java EE is often better done using a servlet that responds to messages (JMS). Then you can send a message to let the servlet do some work.

手动创建线程在 Java EE 环境中并不总是能很好地工作(有时被容器禁止)。在 Java EE 中创建后台任务通常最好使用响应消息 (JMS) 的 servlet 来完成。然后您可以发送消息让 servlet 做一些工作。

回答by danny.lesnik

Please look at this post and Bozho answer

请看这个帖子和Bozho的回答

Open new thread in Tomcat

在Tomcat中打开新线程

Hope it helps.

希望能帮助到你。