Why is this code inconsistent with the execution result in the book?

the code is as follows:

package com.obj;

import java.util.ArrayList;
import java.util.List;

public class MyList {
    private   List list = new ArrayList();
    public  void  add(){
        list.add("");
    }

    public  int size(){
        return list.size();
    }
}
package com.thread;

import com.obj.MyList;

public class ThreadA extends Thread {
    private MyList list;
    public ThreadA(MyList list){
        this.list=list;

    }

    @Override
    public void run() {


        try {
            for (int i = 0; i <10 ; iPP) {
                list.add();
                System.out.println(""+(i+1)+"");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package com.thread;

import com.obj.MyList;

public class ThreadB extends  Thread {
    private MyList list;
    public ThreadB(MyList list){
        this.list=list;

    }

    @Override
    public void run() {
        super.run();
        try {
                while (true){

                    if (list.size() == 5) {
                    System.out.println("==5,b");
                    throw new InterruptedException();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package com.demo;

import com.obj.MyList;
import com.thread.ThreadA;
import com.thread.ThreadB;


public class Run1 {
    public static void main(String[] args) {
        MyList service = new MyList();
        ThreadA a = new ThreadA(service);
        a.setName("A");
        a.start();
        ThreadB b = new ThreadB(service);
        b.setName("B");
        b.start();
    }
}

clipboard.png
listMyList.javalistvolatile

clipboard.png

clipboard.png
volatile,Biflist.size()

clipboard.png

clipboard.png
so it"s not clear what caused this

.
Mar.27,2022

cpu runs very fast, and there are too many cases of multithreading. It is possible that thread a preempts cpu or thread b preempts cpu,. There is a lot of uncertainty about their previous operation, and volatile does have this function, that is, the status of list can be shared by multiple threads in real time.


< H2 > this is the result of code execution in the book < / H2 >


this actually involves the principle of memory Barrier,

synchronized (this) {
}

can get the same result.
this is also in line with the expectations of the jvm memory design.
as for volatile, you can get the same result, and it's the in-memory Barrier that works.

Menu