注册 | 登录 | 设为首页 | 加入收藏
您当前的位置:飞翔学院-IT中国 → IT资讯互联网 → 文章内容

Servlet和ThreadLocal的测试

作者:佚名 来源:不详 发布时间:2007-10-13 14:21:36
        public class TestThreadServlet extends HttpServlet {
  
    private static ThreadLocal thread    = new ThreadLocal();
  
    private int         flag     = 0;
  
    public void doGet( HttpServletRequest request,
  
             HttpServletResponse response)
  
        throws ServletException, IOException {
  
      flag++;
  
      String str = "This is the first String." + new Object();
  
      if (thread.get() == null)
  
        thread.set(str);
  
      PrintWriter out = response.getWriter();
  
      out.println("<p>");
  
      out.println("<BR>flag : " + flag);
  
      out.println("<BR>sessionid : " + request.getSession().getId());
  
      out.println("<BR>servlet : " + this.toString());
  
      out.println("<BR>thread : " + thread.get());
  
      out.println("</p>");
  
    }
  
  }
  
  执行结果:
  
  Session 1:
  
  flag : 2
  sessionid : amGeaiVwKvL9
  servlet : test.other.TestThreadServlet@5f2db0
  thread : This is the first String.java.lang.Object@1ad6b4b
  
  Session 1:
  
  flag : 3
  sessionid : aR3GkcUQoXT-
  servlet : test.other.TestThreadServlet@5f2db0
  thread : This is the first String.java.lang.Object@6214f5
  
  由执行结果可以看出
  
  1 服务器对每个Servlet只创建一个实例。flag不停增加
  
  2 Session范围内的ThreadLocal中对象唯一。不同的请求,Object的hashCode相同。
  
  3 不同的Session共享ThreadLocal,但内部对象不同
  
  另:后来有人提醒我,实际上在web.xml为同一个servlet配置不同的名字,将会是两个不同的实例。也就是说,servlet的实例与配置有关。

查看本文来源


  • 打印文档
  • 推荐好友
  • 返回顶部
  • 增大字体
  • 减少字体
关于本站 | 工作机会 | 合作网站 | 广告服务 | 市场合作| 联系我们 | 抽奖活动
版权所有: 武汉威俊科技有限公司 Copyright 2005-2007 www.ITCNW.COM All rights reserved