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.