赞
踩
- package ThreadSafeServlet07;
- /**
- * 多个线程访问同一个资源时 线程安全问题
- */
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.io.PrintWriter;
-
- public class ThreadSafeServlet01 extends HttpServlet {
- private PrintWriter pw; //将printwrite定义到成员变量中, 当多个浏览器(多个线程)同时访问时容易出现抢占资源,如果把变量定义到成员变量记得实现线程同步
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- this.doPost(req,resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- String name = req.getParameter("name");
- pw = resp.getWriter();
-
- synchronized (this){ //使用synchrenized来实现多个线程同步
- try{
- Thread.sleep(5000);
- pw.println(name);
- pw.flush();
- pw.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。