Understanding of Java multithreading keyword volatile

Recently, I was learning about Java multi-threading and learned the volatile keyword. I also encountered this problem in previous interviews.

First, let's look at an example:

public class MyThread extends Thread {
    volatile public static int count;
    private static void addCount() {
        for (int i=0; i<100; i++) {
            count++;
            System.out.println("当前线程:" + Thread.currentThread().getName() + ",count=" + count);
        }
        System.out.println("count=" + count);
    }

    @Override
    public void run() {
        addCount();
    }

    public static void main(String[] args) {
        MyThread[] myThreads = new MyThread[100];
        for (int i=0; i<100; i++) {
            myThreads[i] = new MyThread();
        }

        for (int i=0; i<100; i++) {
            myThreads[i].start();
        }
    }
}

The final result of the output is different for multiple runs , indicating that the keyword volatile does not make the count value synchronized.

The keyword volatile is to be able to perceive that the variable has been changed (visibility) between multiple threads, so that the thread uses the latest value.

To understand this keyword, you also need to understand the cache structure of multi-core CPUs. I will not introduce the relevant information, please refer to the reference after the text.

Each thread has its own working memory, and variables decorated with the volatile keyword are stored in the main working memory (shared memory). Every time the thread uses this variable, it will go to the main working memory to read the latest value of the area and copy it to the cache of the current thread.

Here are the following situations:

The first type: the variables in the main working memory are not modified, then each thread copies the latest value from the main working memory to the current thread cache for use, and then each thread waits for the notification of the modification of the main memory variable, and there is no notification. use the value currently in the cache;

The second: among many threads, a thread wants to modify this variable, what should I do? First, lock the variable first, then modify the value. After the modification is completed, notify other threads that the value of the main working memory variable has changed. At this time, other threads will actively copy the value of the variable in the main working memory after receiving the notification, overwriting the value in the shared memory of the current thread (that is, regardless of whether the value of the current thread has been modified, it will be overwritten with the value of the main working memory). value in the current thread cache).

Take the previous code example as an example:

There are 100 threads executing the addCount action, and there must be one thread to modify the main memory variable first; then other threads still use the value in the current thread cache before receiving the variable modification notification; that is, assuming that thread A will count the value (modified from 0 to 1) to modify, before the modification is completed (that is to say, no notification has been issued), the value used by other threads is still 0. When thread A is modified and the main thread variable is already 1, other threads will be notified to read the latest value. At this time, the thread will give up the latest value that has been running, even if it is larger than 1, it must give up , while the main memory variable value 1 is used. Therefore, in the previous example, the reason why the final output result is not unique is also this.

To elaborate a little more:

100 threads, thread A has updated the count value in the main working memory to 4, and thread B has just finished the calculation, the count value in the thread is 2, and has obtained the lock to modify the main memory variable, then thread B will modify the main memory variable. The count value in working memory is 2.

Many articles say that volatile is not atomic. I don't understand what this keyword has to do with atomicity.

For the underlying principle of the keyword volatile, please refer to the article: http://www.cnblogs.com/xrq730/p/7048693.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325476882&siteId=291194637