/*Multi-threaded security issue: while (true) {if (tick>0) {//thread 0,1,2,3 at the remaining ticket is 1 o'clock, it's stuck here , then get the CPU execution right, print out 0,-1,-2 System.out.println (Thread.CurrentThread (). GetName () + ".... Sale:" + tick--); }}: When multiple statements are working on the same thread to share data, one thread executes only part of the multiple statements, has not finished executing, and freezes another thread to participate in the execution, resulting in a shared data error. Workaround: Limit the block of statements that share data to multiple operations, allow only one thread to execute at a time, execute after execution, and then run other threads----Java provides a professional solution for multithreading security problems synchronizing code blocks: Synchronized (object) {Code to be synchronized} (personal understanding Lock: A lock is a constant change in the 0,1 of the flag, according to the true and false judgment can choose whether to enter the operating area. The meta-knowledge object in the operating system is similar to the flag bit initially at 1, when the thread enters and first causes the flag bit to be reduced to 0, assuming that the thread is stuck at this point, because the flag bit is 0, the other threads cannot get in. When the thread wakes up, it will flag position 1, allowing other processes to enter) like a toilet on a train: someone (1) no one (0) object is like a lock. A thread holding a lock can execute a thread that does not hold a lock in the synchronization, even if the CPU is executed, and cannot enter because there is no prerequisite for acquiring the lock-----synchronization: 1. Must have two or more than two threads 2. It must be that multiple threads using the same lock must ensure that only one thread in the synchronization performs the---Synchronization mechanism benefits: solves the problem of multithreading security problems: Multiple threads each time to determine the lock, more consumption of resources*/classTicketImplementsrunnable{Private intTicket =1000; Object obj = new Object (); //creating objects with God Public voidrun () { while(true) { synchronized (obj) {if(ticket>0) {System.out.println (Thread.CurrentThread (). GetName ()+".... The remainder of the ticket can be sold: "+ ticket--); } } } }}classtecketdemo2{ Public Static voidMain (string[] args) {Ticket T=NewTicket (); Thread T1=NewThread (t); Thread T2=NewThread (t); Thread T3=NewThread (t); Thread T4=NewThread (t); T1.start (); T2.start (); T3.start (); T4.start (); System.out.println ("Hello world!"); }}
Java Multithreading Security Issues-synchronizing code blocks