In multi-threaded development, there are always multiple ways to manipulate the same data in different threads so that the data is manipulated in different order in different threads.
Or timing can lead to a variety of different phenomena that do not achieve the results you expect, and do not achieve consistency.
Synchronized keyword for a method, this synchronized ensures that only one thread that calls this method is operating this method,
There is no case for multiple threads entering this method at the same time, let's take an example to illustrate the situation.
The first is an account class, this kind of demo accounts, to provide a way to increase wages and reduce wages, of course, this method is controlled by synchronized
Package Com.bird.concursey.charpet2;public class Account {private double balance;public double getbalance () {return Balance;} public void setbalance (double balance) {this.balance = balance;} Public synchronized void Addamount (double amount) {Double temp = balance;try {thread.sleep (ten);} catch (Interruptedexcept Ion e) {e.printstacktrace ();} Temp + = Amount;balance = temp;} Public synchronized void Subtractamount (double amount) {Double temp = balance;try {thread.sleep (ten);} catch (Interruptede Xception e) {e.printstacktrace ();} Temp-= Amount;balance = temp;}}
and protection.
Then there are two simulation classes to simulate the use of this class to increase or decrease the balance of the account
Package Com.bird.concursey.charpet2;public class Bank implements Runnable {private account Account;public Bank account) {This.account = account;} @Overridepublic void Run () {for (int i = 0; i <; i++) {account.subtractamount (1000);}}}
Package Com.bird.concursey.charpet2;public Class Company implements Runnable {private Account Account;public company ( Account: {this.account = account;} @Overridepublic void Run () {for (int i = 0; i <; i++) {account.addamount (1000);}} public static void Main (string[] args) {Account account = new account (); account.setbalance (1000); Company company = new Company; Thread companythread = new Thread (company); Bank Bank = new Bank (account); Thread bankthread = new Thread (bank); System.out.printf ("Account:initial Balance:%f\n", account.getbalance ()); Companythread.start (); Bankthread.start () ; try {companythread.join (); Bankthread.join (); System.out.printf ("Account:final Balance:%f\n", account.getbalance ());} catch (Interruptedexception e) {e.printstacktrace ();}}}
So you can get the right results no matter how you use them.
Java multi-Thread ~~~~synchronized method