【问题标题】:servlet multithreadingservlet 多线程
【发布时间】:2011-12-02 15:16:32
【问题描述】:

我了解 Servlet 请求默认是多线程的。我使用 NetBeans 创建了一个简单的 servlet,它在 Tomcat 和 JBoss 上似乎都是单线程的。

我使用此代码对其进行了测试:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

   System.out.println("access processRequest: " + this + " threadID: " + Thread.currentThread().getId());

    try {
        Thread.sleep(5000);
    } catch (InterruptedException ex) {
        Logger.getLogger(OctaveServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("exit processRequest: " + this + " threadID: " + Thread.currentThread().getId());

}

(从 doGet 调用 processRequest)

我几乎同时从浏览器中的 2 个选项卡访问它,如果多线程可以工作,我希望它打印带有 2 个不同线程 ID 的“访问”,然后是两者的“退出”线程。 相反,我得到了这个输出:

14:53:41,839 INFO [stdout] (http--127.0.0.1-8080-1) 访问 processRequest: OctaveServlet@31ccfe threadID: 34 14:53:46,840 INFO [stdout] (http--127.0.0.1-8080-1) 退出 processRequest: OctaveServlet@31ccfe threadID: 34 14:53:46,867 INFO [stdout] (http--127.0.0.1-8080-1) 访问 processRequest: OctaveServlet@31ccfe threadID: 34 14:53:51,867 INFO [stdout] (http--127.0.0.1-8080-1) exit processRequest: OctaveServlet@31ccfe threadID: 34

如您所见,它只是一个线程。 不用说,我没有实现 SingleThreadModel。

以下是我的系统的详细信息: NetBeans 7.0.1、JVM:Sun java 1.6.0_26、Tomcat 7.0.14、JBoss AS 7、Ubuntu 11.04

非常感谢您的帮助,

奥德。

【问题讨论】:

    标签: multithreading servlets


    【解决方案1】:

    每个 HTTP 连接使用一个线程(服务器使用 NIO 时不完全是这样,但你明白了)。您的浏览器显然在两个选项卡中使用相同的 HTTP 连接。生成两个不同的浏览器实例(例如 Firefox 和 Chrome),您会发现它的工作方式符合您的预期。

    【讨论】:

    • 谢谢!不会猜到浏览器是罪魁祸首!
    猜你喜欢
    • 1970-01-01
    • 2012-01-16
    • 2013-06-02
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2013-09-27
    • 2020-05-25
    相关资源
    最近更新 更多