java 同步块的锁是什么,java – 同步块 – 锁定多个对象
我添加了另一個答案,因為我還沒有添加評論給其他人的帖子。
>事實上,同步是用于代碼,而不是對象或數據。在同步塊中用作參數的對象引用表示鎖定。
所以如果你有如下代碼:
class Player {
// Same instance shared for all players... Don't show how we get it now.
// Use one dimensional board to simplify, doesn't matter here.
private List[] fields = Board.getBoard();
// Current position
private int x;
public synchronized int getX() {
return x;
}
public void setX(int x) {
synchronized(this) { // Same as synchronized method
fields[x].remove(this);
this.x = x;
field[y].add(this);
}
}
}
然后盡管在同步塊上存在,但對字段的訪問不受保護,因為鎖不一樣(它在不同的實例上)。因此,您的主板的播放器列表可能會變得不一致,并導致運行時異常。
相反,如果你寫下面的代碼,它將工作,因為我們只有一個共享鎖為所有玩家:
class Player {
// Same instance shared for all players... Don't show how we get it now.
// Use one dimensional board to simplify, doesn't matter here.
private List[] fields;
// Current position
private int x;
private static Object sharedLock = new Object(); // Any object's 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 can't access fields at the same time
// and so can't create inconsistencies on fields.
fields[x].remove(this);
this.x = x;
field[y].add(this);
}
}
}
=>確保只使用一個鎖來訪問所有玩家,否則您的棋盤狀態將不一致。
總結
以上是生活随笔為你收集整理的java 同步块的锁是什么,java – 同步块 – 锁定多个对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VeraCrypt文件硬盘加密使用教程
- 下一篇: 游标的使用方法