This article introduces Java's most basic synchronization method, which is to use the synchronized keyword to control concurrent access to a method, and if an object is declared with the synchronized keyword, then only one thread of execution allows access to it. Other threads attempting to access this object will be suspended until the first thread has finished accessing it.
Here is a small example to learn the concept, the company to the bank to save money, the situation.
1: Create account class, it is the bank account model, only a double-precision floating-point property, balance.
2: Implement the Get Set method for balance.
3: Implement the Addamount () method, add the incoming quantity to the balance balance, and allow only one thread at a time to change the value, using the Synchronized keyword.
4: Implement the Subtractamount () method, deduct the incoming quantity from the balance balance, and allow only one thread to change the value at the same time.
Specific code:
1 Public classAccount {2 3 /**4 * Balance of the bank account5 */6 Private Doublebalance;7 8 /**9 * Returns The balance of the accountTen * @returnThe balance of the account One */ A Public DoubleGetBalance () { - returnbalance; - } the - /** - * Establish the balance of the account - * @parambalance the New Balance of the account + */ - Public voidSetbalance (Doublebalance) { + This. Balance =balance; A } at - /** - * Add An import to the balance of the account - * @paramamount Import to add to the balance - */ - Public synchronized voidAddamount (Doubleamount) { in Doubletmp=balance; - Try { toThread.Sleep (10); +}Catch(interruptedexception e) { - e.printstacktrace (); the } *tmp+=amount; $ }Panax Notoginseng - /** the * Subtract An import to the balance of the account + * @paramamount Import to subtract to the balance A */ the Public synchronized voidSubtractamount (Doubleamount) { + Doubletmp=balance; - Try { $Thread.Sleep (10); $}Catch(interruptedexception e) { - e.printstacktrace (); - } thetmp-=amount; -Balance=tmp;Wuyi } the -}
5: Implement an ATM simulation class bank, which uses the Subtractamount () method to deduct the balance of the account and implement the Runabl interface.
Specific code:
1 Public classBankImplementsRunnable {2 3 /**4 * The account affected by the operations5 */6 PrivateAccount account ;7 8 /**9 * Constructor of the class. Initializes the accountTen * @paramAccount the account of affected by the operations One */ A PublicBank (account) { - This. account=Account ; - } the - - /** - * Core Method of the Runnable + */ - Public voidrun () { + for(inti=0; i<100; i++){ AAccount.subtractamount (1000); at } - } - -}
6: Implement the Company simulation class, Call Addamount () method to save money, realize Runabl interface.
Specific code:
1 Public classCompanyImplementsRunnable {2 3 /**4 * The account affected by the operations5 */6 PrivateAccount account ;7 8 /**9 * Constructor of the class. Initializes the accountTen * @paramAccount the account of affected by the operations One */ A PublicCompany (account account ) { - This. account=Account ; - } the - /** - * Core Method of the Runnable - */ + Public voidrun () { - for(inti=0; i<100; i++){ +Account.addamount (1000); A } at}
7: Call the Test in the Main method: through the thread's join method, during the deposit period, the pull-money thread is simulated and then the structure is printed out.
1 Public classMain {2 3 /**4 * Main Method of the example5 * @paramargs6 */7 Public Static voidMain (string[] args) {8 //creates a new account ...9Account account=NewAccount ();Ten //An initialize it balance to OneAccount.setbalance (1000); A - //creates a new company and a Thread to run its task -Company Company=NewCompany (account); theThread companythread=NewThread (company); - //creates a new Bank and a Thread to run its task -Bank bank=NewBank (account); -Thread bankthread=NewThread (bank); + - //Prints the initial balance +System.out.printf ("Account:initial Balance:%f\n", Account.getbalance ()); A at //starts the Threads - Companythread.start (); - Bankthread.start (); - - Try { - //Wait for the finalization of the Threads in Companythread.join (); - Bankthread.join (); to //Print the final balance +System.out.printf ("Account:final Balance:%f\n", Account.getbalance ()); -}Catch(interruptedexception e) { the e.printstacktrace (); * } $ }Panax Notoginseng}
As a result, in the same time, the save and fetch should be equal after execution. If we do not use the Synchronized keyword in the method, then the result is wrong.
Account:initial balance:1000.000000
Account:final balance:1000.000000
Java Concurrency Programming combat (using synchronized to implement synchronization methods)