我在 Java 中使用二维数组。但是现在,我想将这个类用于多线程。我怎样才能做到这一点?
我知道如何执行线程安全功能(添加同步关键字)。如果同时触发 clear 和 getItem 函数会发生什么?在这种情况下,我该如何做线程安全的实例?
public class ThreadSafeArray {
int ROW_MAX_COUNT = 1024;
int rowCount = 0;
int counterForRow = 0;
private Object [][] objInstances = new Object[ROW_MAX_COUNT][];
public synchronized void addItem(Object obj) {
if(counterForRow == ROW_MAX_COUNT) {
objInstances[++rowCount] = new Object[ROW_MAX_COUNT];
counterForRow = 0;
}
objInstances[rowCount][counterForRow++] = obj;
}
public synchronized void clear() {
objInstances = new Object[ROW_MAX_COUNT][];
rowCount = 0;
counterForRow = 0;
}
public synchronized Object getItem(int index) {
int row = index / ROW_MAX_COUNT;
int column = index % ROW_MAX_COUNT;
if((row <= rowCount) && (column <= counterForRow)) {
return objInstances[row][column];
}
return null;
}
}
SMILET
慕田峪9158850
相关分类