Java synchronization of the three ways

1. Modified synchronized keyword or category code block;

2. Volatile keyword modified variables;

3. Add reentrant lock class

For example child: multiple threads in a process shared variable time, there will be thread-safety issues. (Corresponds to the operation of a plurality of windows ticket)

Non-synchronous state:

Copy the code
public static void main(String[] args){
        Increase increase = new Increase();
        int count = 10;
        while (count != 0){
            new Thread(() -> {
                increase.increasementAndPrint();
            }).start();
            count --;
        }
    }

    static class Increase {
        private int i = 0;

        void increasementAndPrint() {
            System.out.print(i++ + "\n");
        }
    }
Copy the code

This situation may lead to the same output i of the plurality of threads:

0
0
1
2
3
4
5
6
7
8

Use Sync:

Copy the code
1. Using the synchronized keyword
// ensure atomicity and ordering
static class Increase {
        private int i = 0;

        synchronized void increasementAndPrint() {
            System.out.println(i++);
        }
    }
2. Use the volatile
// does not guarantee atomicity (a volatile variable is declared major visibility ordering)
static class Increase {
    private volatile int i = 0;

    void increasementAndPrint() {
        System.out.println(i++);
    }
}

The volatile keyword may not be able to guarantee the thread safety problems, in fact, in most cases volatile can guarantee thread-safety issues or variables. Therefore, in the case of the following two conditions are met, volatile can guarantee thread-safety issues variables:

  1. Result of the operation does not depend on the current value of the variable, or to ensure that only a single thread modifies the value of the variable.
3. Lock reentrant
// ensure atomicity and ordering
static class Increase {
    private ReentrantLock reentrantLock = new ReentrantLock();
    private  int i = 0;

    void increasementAndPrint() {
        reentrantLock.lock();
        System.out.println(i++);
        reentrantLock.unlock();
    }
}

Guess you like

Origin www.cnblogs.com/2019lgg/p/11039543.html