Vector 的 get 方法为什么也要同步呢?
資深大佬 : brucefu 1
不修改数据也要同步方法吗?不同步有问题?可见性问题? public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index);
return elementData(index); }
大佬有話說 (10)
不修改数据也要同步方法吗?不同步有问题?可见性问题? public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index);
return elementData(index); }
锁不仅仅是关于同步与互斥的,也是关于内存可见的。为了保证所有线程都能 够看到共享的、可变变量的最新值,读取和写入线程必须使用公共的锁进行同步。
如果能确定线程安全,就该用 ArrayList 而不是 Vector