Servlet on-line ticketing problems caused thread-safety problems _jsp programming

Source: Internet
Author: User
Tags ticket

Share relevant code first:

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;//assumes only three tickets public void doget (httpservletrequest
 Request, HttpServletResponse response) throws Servletexception, IOException {printwriter out = Response.getwriter ();
 
 
 Response.setcontenttype ("TEXT/HTML;CHARSET=GBK"); Simple point and deal with ticketing problem//When a variable requires multiple users to share, you should add the synchronization mechanism when accessing the variable/If a variable does not need to be shared, it is defined directly in the Doget () and Dopost () methods, so that there is no thread security problem Synchron Ized (This) {//workaround for synchronization problems if (Ticket > 0) {System.out.println ("You got the tickets!")
  "); Out.println ("You got the Ticket!")
  
  ");
  Hibernate try {thread.sleep (10*1000);
  catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
  } ticket--; else {System.out.println ("You didn't get the ticket!")
  "); Out.println ("You didn't get the tickets!")
  "); }} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex

 ception {this.doget (request, response);

 }

}

The results are as follows: Access to this resource at the same time in different viewers after the third time show the ticket no!

Cause threading problem thinking, small series in the previous study has also encountered, now threading problem has a certain understanding, I hope you can also be inspired by the relevant articles.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.