Thinking about thread security issues caused by Servlet online ticket sales,
First share the relevant code:
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 ticketaskextends HttpServlet {public int ticket = 3; // assume that there are only three public void doGet (HttpServletRequest request, HttpServletResponse response) thr Ows ServletException, IOException {PrintWriter out = response. getWriter (); response. setContentType ("text/html; charset = gbk"); // handle ticket sales issues simply // when a variable needs to be shared by multiple users, you should add a synchronization mechanism when accessing this variable // If a variable does not need to be shared, it can be defined directly in the doGet () and doPost () methods, in this case, synchronized (this) {// Method to Solve the synchronization problem if (ticket> 0) {System. out. println ("you bought the ticket! "); Out. println (" you bought the ticket! "); // Sleep try {Thread. sleep (10*1000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();} ticket --;} else {System. out. println ("You have not bought a ticket! "); Out. println (" You have not bought a ticket! ") ;}} Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doGet (request, response );}}
The running result is as follows: access to this resource in different browsers at the same time, after the third time, the ticket is no longer displayed!
I think about thread problems. I have also encountered some problems in my previous studies. Now I have some understanding about thread problems. I hope you can get some inspiration through relevant articles.
Articles you may be interested in:
- Mysql is stuck. Most threads are in the sending data state for a long time.
- Three methods for passing parameters to multiple threads in java
- Java Thread Synchronization Methods
- Three methods for disabling Java threads
- Several implementation methods of thread-safe Singleton Mode