1. 程式人生 > 其它 >【Servlet】Servlet的多執行緒併發情況

【Servlet】Servlet的多執行緒併發情況

技術標籤:# Java-JavaWebservletjava多執行緒thread

由於Servlet在Tomcat中是以單例模式存在的,所以當多個Servlet執行緒同時訪問了Servlet的共享資料,如成員變數,可能會引發執行緒安全問題。

在這裡插入圖片描述

下面是之前做的一個Demo:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class LoginServlet extends HttpServlet { private static String usernameRef; private static String passwordRef; public static void doPost(String username, String password) { try { usernameRef = username; if ("a"
.equals(username)) { Thread.sleep(5000); } passwordRef = password; System.out.println("username=" + usernameRef + " password=" + passwordRef); } catch (InterruptedException e) { e.printStackTrace(); } }
/** * 輸出樣例: * username=b password=bb * username=b password=aa * @param request * @param response * @throws ServletException * @throws IOException */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LoginThreadA threadA = new LoginThreadA(); LoginThreadB threadB = new LoginThreadB(); threadA.start(); threadB.start(); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
public class LoginThreadA extends Thread {

    @Override
    public void run() {
        LoginServlet.doPost("a", "aa");
    }

}
public class LoginThreadB  extends Thread {

    @Override
    public void run() {
        LoginServlet.doPost("b", "bb");
    }

}

執行的時候,有時的確會出現一些不符的username和password組合,的確會存線上程安全問題。