Struts2的线程安全性

【什么是线程安全性?】

在多线程并发访问的情况下,如果一个对象中的变量的值不会随访问的线程而变化则是线程安全的。反之则称为非线程安全的。

 

【Servlet是线程安全的吗?】

 1 [非线程安全的]
 2 public class HiServlet extends HttpServlet {
 3     int i = 20;
 4     
 5     @Override
 6     protected void service(HttpServletRequest req, HttpServletResponse resp){
 7         System.out.println("i = " + i);
 8         i++;
 9     }
10 }

 

 1 [线程安全的]
 2 public class HiServlet extends HttpServlet {
 3     //int i = 20;
 4     
 5     @Override
 6     protected void service(HttpServletRequest req, HttpServletResponse resp){
 7         int i = 20;
 8         
 9         System.out.println("i = " + i);
10         i++;
11     }
12 }

Servlet是使用单例模式进行实现的。请求过程中只会创建一个Servlet对象。所以Servlet是否是线程安全的与代码有关。

Struts1也是使用单例模式实现的。

 

【Struts2是线程安全的吗?】

 

 1 public class HiAction {
 2     private int i = 20;
 3 
 4     public HiAction() {
 5         System.out.println("HiAction对象被创建了......");
 6     }
 7     
 8     public String execute(){
 9         System.out.println("i = " + i);
10         
11         i++;
12         return "success";
13     }    
14 }

 

Struts2中的Action是通过多例模式进行实现的,所以每次调用都会创建一个新的对象。所以它是线程安全的。

 

posted @ 2018-11-01 17:32  猩生柯北  阅读(379)  评论(0编辑  收藏  举报