php网站建设教程 电子书,做百度推广需要什么条件,标志设计的三要素,asp网站 访问 变慢 监测我添加了另一个答案#xff0c;因为我还没有添加评论给其他人的帖子。事实上#xff0c;同步是用于代码#xff0c;而不是对象或数据。在同步块中用作参数的对象引用表示锁定。所以如果你有如下代码#xff1a;class Player {// Same instance shared for all players.…我添加了另一个答案因为我还没有添加评论给其他人的帖子。事实上同步是用于代码而不是对象或数据。在同步块中用作参数的对象引用表示锁定。所以如果你有如下代码class Player {// Same instance shared for all players... Dont show how we get it now.// Use one dimensional board to simplify, doesnt matter here.private List[] fields Board.getBoard();// Current positionprivate int x;public synchronized int getX() {return x;}public void setX(int x) {synchronized(this) { // Same as synchronized methodfields[x].remove(this);this.x x;field[y].add(this);}}}然后尽管在同步块上存在但对字段的访问不受保护因为锁不一样(它在不同的实例上)。因此您的主板的播放器列表可能会变得不一致并导致运行时异常。相反如果你写下面的代码它将工作因为我们只有一个共享锁为所有玩家class Player {// Same instance shared for all players... Dont show how we get it now.// Use one dimensional board to simplify, doesnt matter here.private List[] fields;// Current positionprivate int x;private static Object sharedLock new Object(); // Any objects instance can be used as a lock.public int getX() {synchronized(sharedLock) {return x;}}public void setX(int x) {synchronized(sharedLock) {// Because of using a single shared lock,// several players cant access fields at the same time// and so cant create inconsistencies on fields.fields[x].remove(this);this.x x;field[y].add(this);}}}确保只使用一个锁来访问所有玩家否则您的棋盘状态将不一致。