------- Android training, Java training, and hope to communicate with you! ----------
When multiple thread classes share the same variable, if it is not controlled, the program will produce an error. For example, for the bank to withdraw money, two withdrawal threads may be against the logic of obtaining money from the same account. The Code is as follows:
Package c16thread;/*** program description: * an account class, representing a bank account, and a getting class, representing the payer. The client holds the account entity and two getting thread classes, two thread classes operate on the same account * that is, the two threads share the same variable, the program demonstrates the business error generated when the shared variable is not controlled * @ author renyajun **/public class twopersononeaccount {public static void main (string [] ARGs) {// 1. get account // 2. create a new user and a new user, operate on the same account, and observe the security of multi-thread shared variables. Acount A = new acount (); getting r2 = new getting (a); getting R1 = new getting (a); thread tr2 = new thread (R2 ); thread tr1 = new thread (R1); tr2.start (); tr1.start () ;}// account class, representing the bank account class acount {private float balance = 800; // balance public float getbalance () {return balance;} public void setbalance (float balance) {This. balance = balance;} // Add public void depositmoney (float money) {This. balance + = money;} // withdraw money from the account public Void merge cemoney (float money) {This. balance-= money ;}}// the getting class indicates the money collection behavior. It holds the reference of the account and passes in the class getting implements runnable {acount; Public getting (acount) {This. acount = A ;}@ overridepublic void run () {If (acount. getbalance ()! = 0) {// After determining whether there is money, let the thread wait for 1 second. If no synchronization is performed, the reducemoney () of the next thread will certainly be executed, // An error occurred while generating the shared variable. Try {thread. sleep (1);} catch (interruptedexception e) {e. printstacktrace ();} acount. using cemoney (800); system. out. println (acount. getbalance ();} else {system. out. println ("failed to get the money! ");}}}
Execution result:
-800 apparently violates if (account. getbalance ()! = 0) the business logic specified in this sentence.
Solution 1: Synchronize code blocks
Public void run () {synchronized (acount2) {If (acount2.getbalance ()! = 0) {// After determining whether there is money, let the thread wait for 1 second. If no synchronization is performed, the reducemoney () of the next thread will certainly be executed, // An error occurred while generating the shared variable. Try {thread. sleep (1);} catch (interruptedexception e) {e. printstacktrace ();} acount2.20.cemoney (800); system. out. println (acount2.getbalance ();} else {system. out. println ("failed to get the money! ");}}