Among the threading knowledge in Java, ticket sales programs are very classic. There are also some problems in the program!
Requirements: Simulate 100 tickets on sale at the same time in 3 windows.
Question 1: Why are 300 tickets sold?
Reason: Because tickets are non-static, non-static member variable data will maintain one piece of data in each object, and there will be three pieces of three thread objects.
Solution: Share the tickets number for three thread objects. Use static modification.
Question 2: Is there a thread safety problem?
Solution to thread safety problems: sun provides a thread synchronization mechanism for us to solve this type of problem.
How to synchronize Java threads:
Method 1: Synchronize code blocks
Method 2: Synchronous function
class SellTickets extends Thread{ static int tickets=1;//The number of votes must be defined as static here. Otherwise, non-static member variables and non-static member variable data will maintain a piece of data in each object. There will be three copies of three thread objects. public SellTickets(String threadName) { super(threadName); } public void run() { while(true){ synchronized ("lock") { if(tickets==101){//or if(tickets>100){ System.out.println("Titles have been sold out-_-..."); break; } System.out.println(Thread.currentThread().getName()+"selled the "+tickets+" number ticket"); tickets++; /* if(tickets==101){ //Wrong. When ticket==101, only one thread jumps out. Tickets++ exists in the other two threads. break; } /* if(Thread.currentThread().getName().equals("Window 2")){ //Window 2 can only sell at most one ticket, and the break is over; } */ } //System.out.println(Thread.currentThread().getName()+"Lock..."); } } } public class Demo4 { public static void main(String[] args) { //Create three thread objects and simulate three windows SellTickets s1=new SellTickets("Window 1"); SellTickets s2=new SellTickets("Window 2"); SellTickets s3=new SellTickets("Window 3"); //Open thread ticketing s1.start(); s2.start(); s3.start(); System.out.println("main method..."); } }