final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); }
其中的 volatile关键字:
保证系统内存一致性
举个例子:多个cpu,cpu1执行了update+1操作,cpu2做修改时会拉取内存要修改的数,保证update+1时内存成功修改