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怎么写?烦请高手处理一下...谢谢....

解决方案 »

  1.   


    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;
    }
    }
    }
      

  2.   

    楼上的代码是错误的,原因我不解释,重点在Integer的不可变性。public synchronized  int getCount() {
                return this.count;
        }    public synchronized  void setCount(int count) {
                this.count = count;
        }直接写在方法里就行了
      

  3.   

    完全错误,这和不可变性没有任何关系。
    1.在Integer缓存范围内会导致多个对象同时竞争。因为同的同一缓存相当于是静态的。
    2.即使不存在缓存,自定义锁也不能设置为可以随时赋值的对象。那样根本达不到锁的目的。
    另外这两个方法同步没有任何意义,只要加是volitial关键字就行。
      

  4.   

    哈哈,楼上的竟然怀疑我的结论?呼呼,屁服。我真的希望你是正确的。
    可惜你连问题都没看懂。如何防止2个方法被同时访问,你认为如何做?你的 volitial 是个啥东西? 多个CPU时用的吗?
      

  5.   

    我在看回贴之前已经做出了这个,和2楼的差不多
    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; 
            }
        }