With regard to thread security, here's a very simple question for the bank to withdraw money:
- User input account, password, system to determine whether the match
- User input amount to withdraw money
- The system determines whether the amount of money is reasonable and whether it is greater than the balance
- If the amount of money taken is less than or equal to the balance, the money is successful.
When two users use the same account to withdraw money, the equivalent of two threads and take the money, there may be an error.
The error occurs because the run () method does not have synchronization security. To solve this problem, Java multithreading supports the introduction of synchronization monitors, using the format of the synchronization monitor as follows:
Sysnchronized (BoJ) {
..........
}
Its operating logic is: locking > Modify > Release lock
Synchronized keywords can be decorated with methods, code blocks, cannot decorate constructors, member variables
The synchronization Monitor is released in the following situations:
- The synchronization method of the current thread of execution or the end of the synchronization code block execution
- The synchronization method of the current thread of execution or the synchronization code encountered Break,return terminated the method or block of code
- The wait () method that executes the synchronization monitor object in a program that currently executes the thread's synchronization method or synchronizes the code
The synchronization monitor is not released in the following scenarios
- When a thread executes a synchronous method or synchronizes a block of code, the program calls the Thread.Sleep (), Thread.yield () method
- When a thread executes a code block, other threads execute the thread's suspend () method to suspend the thread
Here's a small example of a bank taking money:
Packagecom.tc.test; Public classacount {PrivateString Accountno; Private Doublebalance; PublicAcount (String Accountno,Doublebalance) { Super(); This. Accountno =Accountno; This. Balance =balance; } PublicString Getaccountno () {returnAccountno; } Public voidSetaccountno (String accountno) { This. Accountno =Accountno; } Public DoubleGetBalance () {returnbalance; }//Public void Setbalance (double balance) {//this.balance = balance;// } Public synchronized voidDrawDoubleDrawamount) { if(Balance >Drawamount) {System.out.println (Thread.CurrentThread (). GetName ()+ "Win Money" +drawamount); Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } //Modify Balancebalance-=Drawamount; System.out.println ("Balance is:" +balance); }Else{System.out.println ("Failed to withdraw money, insufficient balance!!!" "); } }}
Packagecom.tc.test; Public classDrawthreadextendsThread {Privateacount account; Private DoubleDrawamount; PublicDrawthread (String name, acount account,DoubleDrawamount) { Super(name); This. Account =Account ; This. Drawamount =Drawamount; } Public voidrun () {Account.draw (drawamount); } }
Package com.tc.test; Public class drawtest { publicstaticvoid main (string[] args) { acount ac= New Acount ("123", +); New Drawthread ("First", ac,800). Start (); New Drawthread ("Second", ac,800). Start (); }}
Sync Lock
Starting with jdk1.5, Java provides a more powerful mechanism for thread synchronization ———— synchronization is achieved by displaying the definition of a synchronization lock object, in which the lock object acts as a synchronous locking mechanism.
Lock is a tool that controls access to a shared resource by a thread, usually with a lock providing exclusive access to a shared resource, and only one thread at a time locks the lock, and the thread must first obtain the lock object before accessing the shared resource
Java8 has added a new type of Stampedlock class that provides three lock modes for reading and writing: Writing,readoptimistic,reading.
Dead lock
When two threads wait for each other to release the Sync Monitor, a deadlock occurs, the Java Virtual machine does not detect, and no action is taken to handle the deadlock, and in the event of a deadlock, no exception occurs for the entire program, and there is no hint, except that all threads are in a blocking state.
Java thread Synchronization