假设我们有这些类:
public class Record {
int key;
int value;
Record(){
this.key=0;
this.value=0;
}
Record(int key,int value){
this.key=key;
this.value=value;
}
public class Table {
static final Record[] table = new Record [100];
static final Object[] locks = new Object[table.length];
static{
for(int i = 0; i < table.length; i++) {
locks[i] = new Object();
}
table[0]=new Record(0,0);
table[1]=new Record(1,10);
table[2]=new Record(2,20);
table[3]=new Record(3,30);
}
}
我想在 TRansaction 类中实现这些方法
void setValueByID(int key, int value)
键值对(记录)被锁定(不能从其他事务读取/写入),直到 setValueByID 方法完成。
int getValueByID(int key)
键值对(记录)被锁定直到事务提交
void commit()
它解锁当前事务中锁定的所有键值对(记录)
所以,我的实现是:
class Transaction extends Thread {
//there is no problem here
public void setValueByID(int key, int value){
synchronized(Table.locks[key]) {
Table.table[key].key=key;
}
}
//the problem is here...
//how can i make other thread wait until current thread calls Commit()
public int getValueByID(int key){
int value=0;
synchronized(Table.locks[key]){
value= Table.table[key].key;
}
return value;
}
void commit(){
}
艾哈迈德