Zhe*_*lov 2 java concurrency synchronized
考虑一个代表简单单元格的类:
class Cell {
private int x;
Cell(int x) {
this.x = x;
}
int getX() {
return x;
}
void setX(int x) {
this.x = x;
}
}
Run Code Online (Sandbox Code Playgroud)
如果要使其成为线程安全的,是否应该仅使方法同步或使构造函数同步?
class Cell {
private int x;
Cell(int x) {
synchronized(this) { // <- Is this synchronization necessary?
this.x = x;
}
}
synchronized int getX() {
return x;
}
synchronized void setX(int x) {
this.x = x;
}
}
Run Code Online (Sandbox Code Playgroud)
如果是,为什么构造函数中没有synchronized块java.util.Vector?
| 归档时间: |
|
| 查看次数: |
242 次 |
| 最近记录: |