Synchronization: The concept of object locks. If multiple threads share an object, the operating system generates a lock for each object with one word, and the lock and object one by one correspond. If a thread wants to manipulate an object, it must get the lock on the object.
Lock: Synchronous Statement or synchronization method (a synchronous statement is used here). Resolves an interaction thread with time-related errors.
Note: The mutex must be the same object or it cannot be locked.
public class Save extends thread{
private account A;
private double value;
Public Save (account A, double value) {
this.a = A;
This.value = value;
}
public void Run () {
synchronized (a) {
double b = a.getbalance ();
A.put (value);
System.out.println (A.getname () + "account, existing" + B + ", deposit" + value
+ ", balance" + a.getbalance ());}}
Package cn.hncu.thread.motion;
public class Fetch extends thread{
private account A;
private double value;
Public fetch (account A, double value) {
this.a = A;
This.value = value;
}
public void Run () {
synchronized (a) {//holding lock
double b = a.getbalance ();
System.out.println (A.getname () + "account, existing" + B + ", remove" + a.get (value)
+ ", balance" + a.getbalance ());
} Unlock after a sync statement
Package cn.hncu.thread.motion;
public class Bank {public
static void Main (string[] args) {
//account a1=new account ("Wang"); Save S1=new Save (a1,100); Save S1=new Save (new account ("Wang"); S1.start ();
Account a1=new account ("Wang");
New Save (a1,100). Start ();
New Save (a1,200). Start ();
New Fetch (A1,300). Start ();
New Save (New account ("Xu"). Start ();
}