使用servlet中是否需要考虑线程问题

package day09;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * servlet在tomcat服务器中,是单实例多线程的
 * @author Administrator
 *	
 *	在开发线程安全的servlet的建议:
 *		1)尽量不要使用成员变量,或者静态成员变量。
 *		2)必须要使用成员变量,要么给使用了成员变量的代码块加同步锁,
 *		     但是加锁的代码块的范围应该尽量的小,不然会影响到程序并发的
 *		     效率。
 */
public class ThreadDemo extends HttpServlet {

	private static final long serialVersionUID = 814256409238690261L;
	
	// 成员变量:那么该数据就可能被不同的用户线程共享到。有可能引发多线程并发问题。
	// int count = 1;
	static int count = 1;
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		/**
		 * 给使用到共享数据的代码添加同步锁
		 * 注意:同步锁必须多线程唯一的 
		 * 
		 * 当前类的类对象一定是唯一的(每个类的类对象一定是唯一的):并且当前类是单例的嘛
		 */
		// 同步代码块
		synchronized (ThreadDemo.class) {
			response.getWriter().write("您当前是第"+count+"个访客!");
			count++;
		}
		
		// 同步方法
		myMethod(response);
		
	}
	/* 同步方法
	 * 注意这里应该是静态的同步方法!!!如果是非静态的话就会产生多把钥匙,注意!!!
	 */
	public static synchronized void myMethod(HttpServletResponse response) throws IOException {
		response.getWriter().write("您当前是第"+count+"个访客!");
		count++;
	}

}

posted @ 2018-05-01 10:19  五彩世界  阅读(245)  评论(0编辑  收藏  举报