(ii) Concurrentthread
1. In practice, 10 windows sell tickets, concurrency security issues, can not sell a ticket to two people
2. E-commerce, 10 mobile phones, sold to 50, was robbed by 50 people
3. Thread synchronization (that is, lock)
The toilet on the train, the toilet is shared resources, the person in the toilet is a concurrent thread, the toilet can only shush 100 times
4. For thread concurrency security issues, you need to use a sync lock, which is a shared resource and only 1 threads to access
5. Shared Resource Sync Lock code block
Synchronized (lock object) {
Manipulating shared resource Codes
}
6. Where does the sync code add?
(1) Code is accessed by multiple threads
(2) There is shared data in the code
(3) shared data is manipulated by multiple statements
Code:saleticket_synchronized
public class saleticket_synchronized extends thread{private static int ticket=100;private String windowname;//3. Increase the synchronization lock object resource private static Object Obj=new object ();//1. Create a construction method that allows you to set the name of public saleticket_synchronized (String Windowname) {super (windowname); this.windowname=windowname;} 2. Override the Run method @overridepublic void run () {while (true) {//4. Using synchronous code block synchronized (obj) {if (ticket>0) {//try {/// Thread.Sleep ()//} catch (Interruptedexception e) {//e.printstacktrace ();//}system.out.println (This.getname () + ": is selling the "+ticket+" Ticket "); ticket=ticket-1;} else {System.out.println (This.getname () + ": Sold Out"); break;}}}}
Code:main_synchronized
public class Main_synchronized {/** * concurrent * 4 windows, selling 100 tickets * */public static void Main (string[] args) {//5. Creating Saleticket Objects Sale ticket_synchronized st1=new saleticket_synchronized ("Window 1"); St1.start (); saleticket_synchronized st2=new saleticket_synchronized ("Window 2"); St2.start (); saleticket_synchronized st3=new saleticket_synchronized ("Window 3"); St3.start (); saleticket_synchronized st4=new saleticket_synchronized ("Windows 4"); St4.start ();}}
"Thread" thread concurrently resolves synchronized