如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果和 单线程运行的结果是一样的,而且其他的 变量的值也和预期的是一样的,就是线程安全的。
或者说:一个类或者程序所提供的接口对于线程来说是 原子操作或者多个线程之间的切换不会导致该接口的执行结果存在二义性,也就是说我们不用考虑同步的问题。
线程安全问题都是由 全局变量及 静态变量引起的。
若每个线程中对全局变量、静态变量只有读操作,而无写操作,一般来说,这个全局变量是线程安全的;若有多个线程同时执行写操作,一般都需要考虑线程同步,否则的话就可能影响线程安全。
//==============实例====================\\
package com.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="TestServlet",urlPatterns={"/*"})
public class TestServlet extends HttpServlet{
private String clientName;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取客户端名称
clientName=req.getParameter("clientName");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resp.setContentType("text/html; charset=utf-8");
resp.getWriter().write("客户端请求类型:"+clientName);
}
}
TO:解决方案 加同步块 最小粒度