package com.lc.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Ticketsell extends HttpServlet { public int ticket = 3;//假设只有三张票 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html;charset=gbk"); //简单点而处理售票问题 //当一个变量需要多个用户共享,则应该在访问该变量的时候加 同步机制 //如果一个变量不需要共享则直接在doGet()和doPost()方法中定义即可,这样的话就不存在线程的安全型问题 synchronized (this) { //解决同步性问题的方法 if(ticket > 0) { System.out.println("你买到票了!"); out.println("你买到票了!"); //休眠 try { Thread.sleep(10*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } ticket--; } else { System.out.println("你没有买到票!"); out.println("你没有买到票!"); } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
运行结果如下:在不同的游览器中同时访问这个资源 在第三次之后显示 票没有了!
时间: 2024-09-29 14:04:29