Tomcat如何在内部创建线程? [英] How does Tomcat create threads internally?
问题描述
我正在编写一个需要在不同请求中维护一些内部状态的Tomcat应用程序,所以我需要在Tomcat创建的不同线程之间共享一些内容。我的问题是,如果我写这样的代码,将 Map
(这是 static
到该类)之间共享由Tomcat创建的线程。
I'm writing a Tomcat application which need to maintain some internal states across different requests, so I need share something between different threads created by Tomcat. My question is, if I write code like this, will Map
(which is static
to the class) be shared between threads created by Tomcat.
public class sessionManager extends HttpServlet {
private static HashMap<Integer, String> Map;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// logic
}
}
我想我真正没有得到的是Tomcat如何从单个类创建许多线程 / strong>即可。
I guess what I really don't get is how does Tomcat create many threads from a single class.
推荐答案
我的问题是,如果我写这样的代码,将
地图
(对于类来说是static
)在Tomcat创建的线程之间共享[?]
My question is, if I write code like this, will
Map
(which isstatic
to the class) be shared between threads created by Tomcat[?]
是的。它将在(可能)多个线程之间共享。
Yes. It will be shared across (potentially) multiple threads.
我想我真正没有得到的是Tomcat如何创建多个线程一节课。
I guess what I really don't get is how does Tomcat create many threads from a single class.
线程与类无关。线程是一系列指令。它表示代码的执行。
Threads aren't associated to classes. A thread is a sequence of instructions. It represents execution of your code.
Tomcat产生了许多用于处理请求的线程。它将生成 sessionManager
类的单个实例。所有线程都将使用此实例来处理请求。然后他们每个人都可以访问 Map
字段。您需要根据需要应用自己的外部同步以使其线程安全。
Tomcat spawns a number of threads which it uses to handle requests. It will generate a single instance of your sessionManager
class. All threads will use this instance to handle the request. They then each have access to the Map
field. You'll need to apply your own external synchronization to make it thread safe, as required.
这篇关于Tomcat如何在内部创建线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!