For synchronization, the following two actions need to be done in the specific Java code:
Identify competing access resources as private;
Synchronize the code that modifies the variable, using the Synchronized keyword synchronization method fire code.
Synchronized keyword Smart Tag fee abstract method, cannot tag member variable
To demonstrate the use of synchronization methods, a credit card account was built, with a credit amount of 100w at the beginning, and several operations such as overdraft, deposit, etc. are simulated. Obviously the bank account user object is a competitive resource, and a number of concurrent operations are account method oper (int x), of course, you should add synchronization on this method, and set the balance of the account as a private variable, prohibit direct access.
Here's the code:
public class Test {public static void main (String args[]) {User u=new user ("Zhang San", 100); MyThread t1=new MyThread ("Thread A", u,20); MyThread t2=new MyThread ("Thread B", u,20); MyThread t3=new MyThread ("Thread C", u,20); MyThread t4=new MyThread ("Thread D", u,20); MyThread t5=new MyThread ("Thread E", u,20); T1.start (); T2.start (); T3.start (); T4.start (); T5.start ();} Static class MyThread extends thread{private User u;private int y=0; MyThread (String name,user u,int y) {super (name); this.u=u;this.y=y;} public void Run () {u.oper (y);}} Static class user{private String code;private int cash; User (String code,int cash) {This.code=code;this.cash=cash;} Public String GetCode () {return code;} public void Setcode (String code) {This.code=code;} Public synchronized void oper (int x) {try{thread.sleep (10L); this.cash+=x; System.out.println (Thread.CurrentThread (). GetName () + "run end, increase" "+x+" ", Current account balance:" +cash);} catch (Interruptedexception e) {e.printstacktrace ();}} Public String toString () {return "user{" + "code=" +code+ ", cash=" +cash+ "}";}}}
The key point is
Public synchronized void oper (int x) {
This method is synchronized so that only one thread is allowed to access it, thus preventing errors from appearing
The code has been validated to enable functionality
A probe into Java thread synchronization of "Good Programmer training Camp"