Thread synchronization is the difficulty of Java multithreaded programming, often developers do not know what is competitive resources, when to consider synchronization, how to sync and so on, of course, these questions do not have a very clear answer, but some of the principles of the issue to be considered, whether there are competing resources to be changed simultaneously?
Before this article, see Java Thread: Synchronization and lock of threads, which is written on this basis.
For synchronization, you need to do two things in a specific Java code:
Identify the resources of the competition access as private;
Synchronize the code that modifies the variable, using the Synchronized keyword to synchronize the method or code.
Of course, this is not the only way to control concurrent security.
Synchronized Keyword usage instructions
Synchronized can only mark methods that are not abstract, and cannot identify member variables.
In order to demonstrate the use of synchronization methods, a credit card account was built, at the initial credit amount of 100w, and then simulated overdraft, deposit and other operations. Obviously the bank account user object is a competitive resource, and multiple concurrent operations are the account method oper (int x), of course should be synchronized with this method, and the balance of the account is set to private variable, prohibit direct access.
/**
* Java Thread: Synchronization of Threads
*
* @author leizhimin
*/
public class Test {
public static void Main (string[] args) {
User U = New User ("John", 100);
mythread t1 = new Mythread ("Thread A", U, 20);
mythread t2 = new Mythread ("Thread B", U,-60);
mythread t3 = new Mythread ("Thread C", U,-80);
mythread t4 = new Mythread ("Thread D", u,-30);
mythread T5 = new Mythread ("Thread E", u, 32);
mythread T6 = new Mythread ("Thread F", u, 21);
T1.start ();
T2.start ();
T3.start ();
T4.start ();
T5.start ();
T6.start ();
}
}
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);
}
}
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;
}
/**
* Business Method
* @param x Add x million
*/
public synchronized void oper (int x) {
try {
Thread.Sleep (10L);
This.cash = x;
System.out.println (Thread.CurrentThread (). GetName () + "run over, add" + x + "", current user account balance is: "+ CAs h);
Thread.Sleep (10L);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
@Override
public String toString () {
return "user{" +
"code= '" + code + ' \ ' +
", cash=" + Cash +
'}';
}
}