java并发多线程,为什么每个线程都是先加后减,会出现多减情况呢?⚠️做图从cup时间片角度解释

⚠️注意 什么是并发,什么是并发安全问题

  • 因为,t1线程在添加元素时,会先读取地址,再添加,这时,读取地址完,没有添加就失去cup时间片,这是就会产生并发错误(t2线程也读取同样的地址让后t1,t2添加到同一个位置所以造成多删的情况)
public static void main(String[] args) throws CloneNotSupportedException {
        Unsafe unsafe = new Unsafe();
        Thread t1=new Thread(()->{
          unsafe.method();
        });
        Thread t2 = new Thread(()->{
            unsafe.method();
        });
        t1.start();
        t2.start();
    }
public class Unsafe {

    ArrayList<String> arrayList = new ArrayList<>();
    public void add(){
        arrayList.add("1");
    }
    public void remove(){
        arrayList.remove(0);
    }
    public void method(){
        for (int i=0;i<200;i++){
            add();
            remove();
        }
    }
}

在这里插入图片描述

做图从cup时间片角度解释

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_20156289/article/details/108020459