在阅读了关于Java同步方法的主题之后,我尝试在我的多人游戏中实现它,因为打开了许多线程并尝试访问相同的资源。 我已经使方法同步,但这并没有帮助我,因为如果我有一个数据成员称为ArrayList clientConnection;和可用的方法是:是否可以同步数据成员而不是方法?
int getArrayListSize() {
clientConnection.size();
}
void addConnection(ServerConnection i_connection) {
clientConnection.add(i_connection);
}
void removeConnection(ServerConnection i_connection) {
int index = clientConnections.indexOf(i_Connection);
clientConnections.remove(index);
}
ServerConnection getClientFromArrayListByIndex(int i_Index) {
ServerConnection client = this.clientConnections.get(i_Index);
}
我试图做一个全球同步的方法,每当一个想使用他需要在操作类型等数据传递的方法之一,他锁定功能。 问题是有2个函数返回void,1个返回int,1个返回ServerConnection,所以我无法创建该全局方法。 我的问题是否有可能在Java中锁定数据成员而不是方法,这样我可以锁定clientConnection数据成员? 谢谢。
在我看来'getArrayListSize'和'getClientFromArrayListByIndex'不属于你的对象的公共接口。如果您能向我们展示实际使用情况,我们可以引导您朝着正确的方向发展。 –