Java concurrent programming practice (using synchronized for synchronization)
This article introduces the most basic synchronization method in java, that is, using the synchronized keyword to control concurrent access to a method. If an object has been declared with the synchronized keyword, only one execution thread is allowed to access it, other threads trying to access this object will be suspended until the first thread completes access. The following uses a small example to learn this concept. The company saves money from a bank and withdraws money. 1: Account class used to create an Account. It is a model of a bank Account and has only one double-precision floating-point attribute. balance. 2: implement the get set Method of balance. 3: implement the AddAmount () method, add the incoming quantity to the balance, and allow only one thread to change this value at the same time, using the synchronized keyword. 4: implement the SubtractAmount () method, deduct the incoming quantity from the balance, and allow only one thread to change this value at the same time. Code:
1 public class Account { 2 3 /** 4 * Balance of the bank account 5 */ 6 private double balance; 7 8 /** 9 * Returns the balance of the account10 * @return the balance of the account11 */12 public double getBalance() {13 return balance;14 }15 16 /**17 * Establish the balance of the account18 * @param balance the new balance of the account19 */20 public void setBalance(double balance) {21 this.balance = balance;22 }23 24 /**25 * Add an import to the balance of the account26 * @param amount import to add to the balance27 */28 public synchronized void addAmount(double amount) {29 double tmp=balance;30 try {31 Thread.sleep(10);32 } catch (InterruptedException e) {33 e.printStackTrace();34 }35 tmp+=amount;36 }37 38 /**39 * Subtract an import to the balance of the account40 * @param amount import to subtract to the balance41 */42 public synchronized void subtractAmount(double amount) {43 double tmp=balance;44 try {45 Thread.sleep(10);46 } catch (InterruptedException e) {47 e.printStackTrace();48 }49 tmp-=amount;50 balance=tmp;51 }52 53 }
5: Implement an ATM simulation class Bank, which uses the subtractAmount () method to deduct the account balance and implement the Runabl interface. Code:
1 public class Bank implements Runnable { 2 3 /** 4 * The account affected by the operations 5 */ 6 private Account account; 7 8 /** 9 * Constructor of the class. Initializes the account10 * @param account The account affected by the operations11 */12 public Bank(Account account) {13 this.account=account;14 }15 16 17 /**18 * Core method of the Runnable19 */20 public void run() {21 for (int i=0; i<100; i++){22 account.subtractAmount(1000);23 }24 }25 26 }
6: implement the company simulation class, call the addAmount () method to save money, and implement the Runabl interface. Code:
1 public class Company implements Runnable { 2 3 /** 4 * The account affected by the operations 5 */ 6 private Account account; 7 8 /** 9 * Constructor of the class. Initializes the account10 * @param account the account affected by the operations11 */12 public Company(Account account) {13 this.account=account;14 }15 16 /**17 * Core method of the Runnable18 */19 public void run() {20 for (int i=0; i<100; i++){21 account.addAmount(1000);22 }23 }
7: Call the test in the main method: Through the join method of the thread, the money-taking thread prints out the structure after simulation.
1 public class Main { 2 3 /** 4 * Main method of the example 5 * @param args 6 */ 7 public static void main(String[] args) { 8 // Creates a new account ... 9 Account account=new Account();10 // an initialize its balance to 100011 account.setBalance(1000);12 13 // Creates a new Company and a Thread to run its task14 Company company=new Company(account);15 Thread companyThread=new Thread(company);16 // Creates a new Bank and a Thread to run its task17 Bank bank=new Bank(account);18 Thread bankThread=new Thread(bank);19 20 // Prints the initial balance21 System.out.printf("Account : Initial Balance: %f\n",account.getBalance());22 23 // Starts the Threads24 companyThread.start();25 bankThread.start();26 27 try {28 // Wait for the finalization of the Threads29 companyThread.join();30 bankThread.join();31 // Print the final balance32 System.out.printf("Account : Final Balance: %f\n",account.getBalance());33 } catch (InterruptedException e) {34 e.printStackTrace();35 }36 }37 }
Result: in the same time period, the storage and the fetch operation should be equal. If we do not use the synchronized keyword in the method, the result is incorrect.