The difference between volatile and synchronized in Java multithreading

Insert picture description here

Volatile

The two keywords volatile and synchronize are not uncommon in concurrent programming and can be understood asvolatile is lightweight synchronizedJava multithreading supports multiple threads to access a member variable or object at the same time, so both keywordsGuaranteed visibility of shared variablesVisibility is when a thread modifies a shared variable, another thread reads the value after the shared variable is manipulated.
With the iteration of the jdk version, the synchronized keyword is also optimized very well, not as heavy

Volatile's implementation principle

Java allows multiple threads to access shared resources to ensure thread safety and consistency. Threads to obtain resources independently through lock objects are
more convenient than locks in some cases. If a variable is declared volatile, then all threads see the value of this variable Are all consistent

The role of Volatile keywords

The role of the volatile keyword prohibits instruction reordering and forces variable values ​​to be fetched from the public stack, rather than fetching variable values ​​from the thread's private data stack

Synchronized

Synchronization code block, synchronization method is very common in our project, the role is to ensure the consistency and atomicity of multi-threaded operation shared resources to
ensure that only one thread can access the shared resources at the same time, other threads are in the blocking phase, only the
Only after the execution of the thread is completed or an exception occurs, the lock object will be released. Other threads can compete for the next round of CPU execution rights (time slice)

Synchronized principle

Synchronized has been criticized as a heavyweight lock. In contrast, it is really not as flexible and convenient as Lock. For specific usage, please refer to my above article Java Multithreading Thread Safety

! ! ! note! ! !

  • When using lock, you must release the lock in finally, otherwise deadlocks are prone to occur, and when using synchronized, do n’t worry, the lock acquiring thread will release the lock after executing the synchronization code, or the JVM will release the lock object when the execution thread is abnormal.
  • When using lock, the thread will not wait forever. When using synchronized, after thread A acquires the object lock, other threads enter the blocking phase and wait forever
  • synchronized is an implicit lock, in needSynchronized resources are added to this control, And Lock is a display lock, which needs to be added before and after the synchronized resourceAcquire lock and release lock operation

How to synchronize

Synchronous code blocks, objects can be of any type,
also written in parenthesesthis, Representing that the current lock object is the current class object

public class RunnableImpl implements Runnable {
 
    // 定义一个多个线程共享票源
    private int ticket = 30;

    // 创建锁对象
    Object obj = new Object();

    /**
     * 卖票
     */
    @Override
    public void run() {
        while (true) {
            // 创建同步代码块
            synchronized (obj) {
                // 先判断票是否存在
                if (ticket > 0) {
                    // 存在
                    System.out.println(Thread.currentThread().getName() + "--->正在卖票" + ticket + "张票");
                    ticket--;
                }
            }
        }
    }
}

Synchronization method, add the synchronized keyword above the method. The
lock object is an instance of the current class

public class RunnableImpl implements Runnable {

    // 定义一个多个线程共享票源
    private int ticket = 100;

    /**
     * 卖票
     */
    @Override
    public void run() {
        while (true) {
            updateTicket();
        }
    }
    // 同步方法
    public synchronized void updateTicket() {
        // 先判断票是否存在
        if (ticket > 0) {
            // 存在
            System.out.println(Thread.currentThread().getName() + "--->正在卖票" + ticket + "张票");
            ticket--;
        }
    }
}

The difference between Volatile and Synchronized

Insert picture description here

  • volatile will not cause thread blocking, synchronized will cause thread blocking
  • volatile can only modify variables, synchronized can modify synchronized code blocks and methods
  • volatile cannot guarantee atomicity (cannot guarantee thread safety), synchronized can guarantee atomicity
  • volatile solves the problem of shared resources between multiple threadsVisibility, Synchronized solves the problem of accessing shared resources between multiple threadsSynchronization
Published 24 original articles · praised 33 · visits 2391

Guess you like

Origin blog.csdn.net/weixin_41241629/article/details/104460593