如果方法 B 没有 synchronized的话,不需要得到对象 o 的锁就可以执行。

解决方案 »

  1.   

    将A方法synchronized,这样就可以保证只有一个线程能访问他了
    而B方法则不需要synchronized
    这样是不是比o用synchronized保护要好得多??
      

  2.   

    to楼上的老兄:
    我不明白你说的对象的锁与对象的使用无任何关系这句话的意思,请解释一下好吗?我对对象锁的理解就是,当这个对象被synchronized关键字保护的时候,那在同一时刻只有一个线程可以访问它,修改它的属性也好,调用它的方法也好,把它当作参数传给别人也好,总之它只能被一个线程使用。不知道我的理解对不对,还请您指教。另外,我第一个问题问的并不是需要还是不需要,而是想了解这样的写法是否能满足我设计上的需求,这个对象只对使用它的发送线程有限制,而对接收线程无限制。谢谢。
      

  3.   

    同意craks的意见,将A synchronized就可以了
    ================================================================CSDN 论坛助手 Ver 1.0 B0402提供下载。 改进了很多,功能完备!★  浏览帖子速度极快![建议系统使用ie5.5以上]。 ★  多种帖子实现界面。 
    ★  保存帖子到本地[html格式]★  监视您关注帖子的回复更新。
    ★  可以直接发贴、回复帖子★  采用XML接口,可以一次性显示4页帖子,同时支持自定义每次显示帖子数量。可以浏览历史记录! 
    ★  支持在线检测程序升级情况,可及时获得程序更新的信息。★★ 签名  ●  
         可以在您的每个帖子的后面自动加上一个自己设计的签名哟。Http://www.ChinaOK.net/csdn/csdn.zip
    Http://www.ChinaOK.net/csdn/csdn.rar
    Http://www.ChinaOK.net/csdn/csdn.exe    [自解压]
      

  4.   

    to craks()
    我也想过你说的办法,可是若将方法synchronized起来,那被保护的只是这个方法的 this对象。而那个连接类不是我写的,是别人提供的api,所以我能做的只是在自己写的类中调用它,所以好象只有用synchronized(object)的方式来对它进行保护。
      

  5.   

    对于所有的发送消息线程,当他们需要使用o来发消息的时候,必须将o同步起来,而对于接收消息的线程,即使在o被发送线程占用的时候,它也应该可以在o上进行侦听,相反,在它使用o侦听的同时,发送线程也可以获得o的锁进行消息的发送so your sender is writer, listener is reader.
    this is a typical situation where writers conflict, readers dont. and you don't want reader conflict with writer.
    i.e.
    W xxxxxx W
    R ------ R
    W ------ Rthe key is that whether your writer can generate inconsistent state. If it does not, then you don't need to put lock on reader. otherwise, better synchronize reader as well.
    By consistent state, I mean, if we interrupt your writer function at any point, the object is still good to use.Normally, immutable structure can work suprisingly well with this requirement.
      

  6.   

    非常感谢 huangzt(),ajoo(jet pig)和 dylanwolf() 的回答,我想我理解了你们的意思,即在发送线程中对o进行synchronized,而在接收线程中则不必,对否?请各位接分
      

  7.   

    no. you did not get me. 
    "在接收线程中则不必". wrong.if your sender does not generate inconsistent state, then 在接收线程中则不必. Otherwise, 必!an example of inconsistent state,void transferMoney(int amount){saving += amount; checking -= amount;}
    let's assume you have $100 in saving, $50 in checking.
    you want to transfer $50 from checking to saving.if we interrupt transferMoney, then we may get a state where you have $150 in saving, $50 in checking. That is not true!!! We should not let a reader get this incorrect state.Actually, if you program mutablly, inconsistent state is everywhere. "+=" itself can generate inconsistent state as well!So, my suggestion is, try to see if you can use immutable structure.Otherwise, unless you are 120% sure, place "synchronized" to reader!