Requirement: Simulate three windows and buy tickets at the same time.
Problem 1:static modifies num to create only one copy in memory, or 3 copies are created.
Issue 2: Thread safety issues. (The code weighs 1 in the red font)
Cause: There are two or more two thread objects, and a resource is shared between threads .
There are multiple statements that operate on shared resources.
Workaround: Add a lock , synchronized, put the lock in place where there is a thread safety problem, when multiple threads together
To access when (thread 1, thread 2, thread 3), to see who first strong to the lock, first grab the "people", get the lock,
Then the door "locks", executes its own, while the rest of the thread is "outside the door" and so on, until it comes out,
At this point the state of the lock becomes "open", and then three of them continue to "Rob", cycle the process.
Note: There are only a few public locks and there are only a few that can solve the problem.
So, since the lock is so good, do we have to add a "lock" to our code?
A: No, there is no need to add the time, otherwise it will reduce efficiency, such as: Judge the lock "open" and "off", that is to consume time.
ImportJava.util.Scanner; Public classEX10 { Public Static voidMain (string[] args) {saleticket T1=NewSaleticket ("Chongkuo 1"); Saleticket T2=NewSaleticket ("Chongkuo 2"); saleticket T3=NewSaleticket ("Chongkuo 3"); T1.start (); T2.start (); T3.start (); }}classSaleticketextendsthread{Static intnum = 50; StaticObject o =NewObject (); PublicSaleticket (String name) {Super(name); } @Override Public voidrun () { while(true) { synchronized("Lock"){ if (num > 0) {System.out.println (Thread.CurrentThread (). GetName () + "sold the first--------" + num + "Ticket") ; try{Thread.Sleep (100); }catch (interruptedexception e) {e.printstacktrace (); } num--; }else{System.out.println ("Sold out"); break; } } } }}
Java Multi-Threading 3 (thread safe)