[Java Basics] Happens-before of java visibility

definition

The Happens-before relationship is used to describe issues related to visibility. We can simply understand that it is executed in order, one by one.

举例:小情侣一起做饭,小美女在洗米,小帅哥在弄电饭锅,
     必须等米洗完后,才能开始煮饭。

In java, happens-before is a relational operator used to define the time sequence between two events, happens-before only works in Java's memory model. Visibility is guaranteed.

If the first operation happens-before the second operation (which can also be described as the happens-before relationship between the first operation and the second operation), then we say that the first operation must be visible to the second operation Yes, when the second operation is performed, it is guaranteed to see the result of the first operation.

The happens-before relationship in Java can be achieved by using the synchronized keyword. The synchronized keyword can set multiple methods or code blocks to be synchronized, that is, only one thread can access them, while other threads need to wait.
Here is a sample code showing how to implement a happens-before relationship using the synchronized keyword:

public class MyConcurrency {
    
      
    private static final Object lock = new Object();  
  
    public void method1() {
    
      
        synchronized (lock) {
    
      
            System.out.println("Method1 is executing");  
        }  
    }  
  
    public void method2() {
    
      
        synchronized (lock) {
    
      
            System.out.println("Method2 is executing");  
        }  
    }  
  
    public void method3() {
    
      
        synchronized (lock) {
    
      
            System.out.println("Method3 is executing");  
        }  
    }  
}

In the sample code above, we created an object named lock as a synchronization lock, and then surrounded it with the synchronized keyword in each method. This means that only one thread can access the method1(), method2(), and method3() methods, while other threads need to wait.

Rules for Happens-before Relationships

(1) Single-thread rule: In a single-thread, according to the order of the program code, the operation executed first is before the operation executed later (
2) Lock operation rules (Lock and synchronized interface, etc.): If operation A is unlocked, the operation B is to lock the same lock, then hb(A,B).
(3) Rules for volatile variables: A write operation to a volatile variable happens-before followed by a read operation on the variable.

Give an example without a happens-before relationship

比如多个线程同时对一个数进行操作,如下
public class Visibility {
    int x = 0;
    public void write() {
        x = 1;
    }

    public void read() {
        int y = x;
    }
}

Guess you like

Origin blog.csdn.net/fumeidonga/article/details/130328428