当前位置:主页 > 查看内容

Servlet网上售票问题引发线程安全问题的思考

发布时间:2021-05-12 00:00| 位朋友查看

简介:先分享相关代码: 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.htt……

先分享相关代码:

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);

 }

}

运行结果如下:在不同的游览器中同时访问这个资源  在第三次之后显示 票没有了!

引发线程问题的思考,小编在之前的学习中也遇到过,现在线程问题有了一定的理解,希望大家也可以通过相关文章得到启发。


本文转载自网络,原文链接:https://m.jb51.net/article/76257.htm
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐