synchronized
synchronized is a key word in Java. It is a kind of synchronization lock. It modifies the following objects:
1. Modify a code block. The modified code block is called synchronization statement block. Its scope of action is the code enclosed by braces {}, and the object of action is the object calling the code block;
2. Modify a method. The modified method is called synchronous method. Its scope of action is the whole method and the object of action is the object calling the method;
3. Modify a static method. Its scope of action is the entire static method, and the object of action is all objects of this class;
4. Modify a class. Its scope of action is the bracketed part after synchronized. The object of action is all objects of this class.
Code is best interpreted
public class Customer {
public static synchronized void shop(Customer c) {
System.out.println("shop The shop is open...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(c.name + " Come shopping...");
System.out.println("Thank you for your coming.");
}
public static void shop2(Customer c) {
System.out.println("shop2 The shop is open...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (c) {
System.out.println(c.name + " Come shopping...");
}
System.out.println("Thank you for your coming.");
}
public static void main(String[] args) {
Customer zs = new Customer("Zhang San");
Customer ls = new Customer("Li Si");
Customer ww = new Customer("Wang Wu");
Customer zl = new Customer("Zhao Liu");
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
shop(zs);
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
shop(ls);
}
});
t1.start();
t2.start();
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
shop2(ww);
}
});
Thread t4 = new Thread(new Runnable() {
@Override
public void run() {
shop2(zl);
}
});
t3.start();
t4.start();
}
public Customer(String name) {
this.name = name;
};
public String name;
}
Operation result:
The shop is open shop2 store is open shop2 store is open Zhao Liu has come to buy things Zhang San has come to buy things Thank you for your coming. Wang Wu has come to buy things Thank you for your coming. The shop is open Thank you for your coming. Li Si has come to buy things Thank you for your coming.