【发布时间】:2018-04-29 02:05:06
【问题描述】:
class Banco{
int slots;
int []av;
public Banco(int n){
slots = n;
av=new int[slots];
for(int i=0;i<slots;i++)
av[i]=0;
}
public int query(int i){
return this.av[i];
}
public int getSlots (){
return this.slots;
}
public synchronized void credito(int i, int valor){
av[i] += valor;
}
public synchronized void debito(int i, int valor){
av[i] -= valor;
}
public void transferir(int valor){
Random r = new Random();
int a = r.nextInt(slots);
int b = r.nextInt(slots);
if(a<b){
synchronized(this.query(a)){
synchronized(this.query(b)){
this.credito(b,valor);
this.debito(b,valor);
}
}
}
else{
a = r.nextInt(slots);
b = r.nextInt(slots);
}
}
}
这是我的代码,但在同步时出现以下错误,我不知道为什么:
意外的类型 同步(this.query(a))
必填:参考
找到:int
错误:意外类型 同步(this.query(b))
必填:参考
找到:int
【问题讨论】:
-
不,不是。您无法在原语上进行同步。
-
如错误消息所示,这是不可能的。它必须是
Object -
好的,这是我的疑问,谢谢。
-
你想做什么?这几乎可以肯定是XY Problem。
-
@AndyTurner 我最喜欢
query的实现 ;-)
标签: java synchronized