public class Demo{
private int count; public int getCount(){
return this.count;
}
public void setCount(int count){
this.count=count;
}
}
如何处理才能让程序访问getCount()方法的时候不能访问setCount(int count)方法,用synchronized怎么写?烦请高手处理一下...谢谢....
private int count; public int getCount(){
return this.count;
}
public void setCount(int count){
this.count=count;
}
}
如何处理才能让程序访问getCount()方法的时候不能访问setCount(int count)方法,用synchronized怎么写?烦请高手处理一下...谢谢....
public class Demo {
private Integer count; public int getCount() {
synchronized (this.count) {
return this.count;
}
} public void setCount(int count) {
synchronized (this.count) {
this.count = count;
}
}
}
return this.count;
} public synchronized void setCount(int count) {
this.count = count;
}直接写在方法里就行了
1.在Integer缓存范围内会导致多个对象同时竞争。因为同的同一缓存相当于是静态的。
2.即使不存在缓存,自定义锁也不能设置为可以随时赋值的对象。那样根本达不到锁的目的。
另外这两个方法同步没有任何意义,只要加是volitial关键字就行。
可惜你连问题都没看懂。如何防止2个方法被同时访问,你认为如何做?你的 volitial 是个啥东西? 多个CPU时用的吗?
public class Demo{
private int count;
private Object o; public int getCount(){
synchronized (this.o){
return this.count;
}
}
public void setCount(int count){
synchronized (this.o){
this.count=count;
}
}
}