多线程在 Web 应用程序中的作用 [英] role of multithreading in web application

查看:28
本文介绍了多线程在 Web 应用程序中的作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 java(Servlets, JSPs) 进行 Web 应用程序开发已有 2 年了.在这 2 年里,我从未需要在任何项目中使用 multithreading(明确地 - 因为我知道 servlet 容器使用线程为不同的请求提供相同的 servlet).

I am using java(Servlets, JSPs) since 2 years for web application development. In those 2 years I never required to use multithreading(explicitly - as I know that servlet containers uses threading to serve same servlet to different requests) in any project.

但是每当我参加 Web 开发人员职位(java)的面试时,都会有几个与 java 中的线程相关的问题.我知道java线程的基础知识,所以回答问题不是问题.但有时我会感到困惑,我在开发 Web 应用程序时是否因为不使用多线程而遗漏了什么?

But whenever I attend an interview for Web Developer position(java), then there are several questions related to threads in java. I know the basics of java threading so answering the questions is not a problem. But sometimes I get confused whether I am missing something while developing web application by not using mutithreading?

所以我的问题是 multithreading 在 Web 应用程序中的作用是什么?任何可以在 Web 应用程序中使用 multithreading 的示例都将不胜感激.

So my question is that what is the role of multithreading in Web Application? Any example where multithreading can be used in web application will be appreciated.

提前致谢.

推荐答案

多线程可以在 Web Apps 中使用,主要是当您对异步调用感兴趣时.

Multi-threading can be used in Web Apps mainly when you are interested in asynchronous calls.

例如,假设您有一个 Web 应用程序,它激活用户在 GSM 网络上的状态(例如激活 4G 计划)并在最后发送确认短信或电子邮件.

知道 Web 呼叫需要几分钟的时间——尤其是在 GSM 网络压力大的情况下——直接从 Web 线程调用它是没有意义的.

Consider for example you have a Web application that activates a user's state on a GSM network (e.g activate 4G plan) and sends a confirmatory SMS or email message at the end.

Knowing that the Web call would take several minutes - especially if the GSM network is stressed - it does not make sense to call it directly from the Web thread.

所以基本上,当用户点击激活"时,服务器会返回类似感谢您激活 4G 计划.您的计划将在几分钟内激活,您将收到确认短信/电子邮件"之类的内容.

So basically, when a user clicks "Activate", the Server returns something like "Thanks for activating the 4G plan. Your plan will be activated in a few minutes and you will receive a confirmation SMS/email".

在这种情况下,您的服务器必须以异步方式生成一个新线程,理想情况下使用线程池,并立即向用户返回响应.

In that case, you server has to spawn a new thread, ideally using a thread pool, in an asynchronous manner, and immediately return a response to the user.

工作流程:

1- 用户点击激活"按钮
2- Servlet 接收请求并在线程池中激活新的激活 4G 计划"任务.
3- Servlet 立即向用户返回 HTML 响应,而无需等待任务完成.
4- Http 交易结束
...

1- User clicks "Activate" button
2- Servlet receives request and activates a new "Activate 4G Plan" task in a thread pool.
3- Servlet immediately returns an HTML response to the user without waiting for the task to be finalized.
4- End of Http transaction
. . .

异步地,4G计划稍后激活,并通过短信或电子邮件等方式通知用户......

Asynchronously, the 4G plan gets activated later and the user gets notified through SMS or email, etc...

这篇关于多线程在 Web 应用程序中的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆