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, when you can use
Synchronizedkeyword for a method, this synchronized ensures that all threads that call this method have only one operation in this method.
There is no case where multiple threads are entering this method at the same time, let's take a sample to illustrate the situation below.
The first is an account class, this class of demo accounts, which provides a way to add wages and lower 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 using this class to add or lower the remaining amount 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