HttpServlet不实现runnable或扩展线程,为什么它是thread-able? [英] HttpServlet does not implement runnable or extend thread, why is it thread-able?
问题描述
对于可运行的对象,它需要实现 Runnable
接口或扩展 Thread
,它不似乎 HttpServlet
做任何这些。
For an object to be runnable, it needs to implement the Runnable
interface or extend the Thread
class, however, it does not seem that HttpServlet
does any of these.
如何来 HttpServlet
可以线程或有我错误?
How come HttpServlet
can be threaded or have i mistaken?
推荐答案
Servlet本身不是线程。容器维护一个servlet类的实例,每个请求(线程)调用相同的servlet对象。所以servlet实例是跨线程共享的。在伪代码中它可能看起来像这样:
The Servlet itself is not a thread. The container maintains one instance of the servlet class and each request (thread) calls the same servlet object. So the servlet instances is shared across threads. In pseudo code it may look like this:
class ServerThread extends Thread {
private javax.servlet.Servlet servlet;
private javax.servlet.ServletRequest req;
private javax.servlet.ServletResponse res;
public ServerThread(javax.servlet.Servlet servlet, /* request and response */) {
this.servlet = servlet;
this.req = req;
this.res = res;
}
@Override
public void run() {
this.servlet.service(req, resp);
}
}
没问题,更复杂: - )
No question, in reality it will be much, much, much more complex :-)
BTW:这就是为什么你的servlet类必须是线程安全的!
BTW: That's the reason your servlet classes have to be thread safe!
这篇关于HttpServlet不实现runnable或扩展线程,为什么它是thread-able?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!