精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (10)
|
|
---|---|
作者 | 正文 |
发表时间:2011-02-28
还用看什么书啊,打开源码,1分钟你就知道区别
|
|
返回顶楼 | |
发表时间:2011-03-01
synchronize不仅是为了线性执行,还是为了确保线程栈中对象的值被刷新回主内存啊。get方法没有锁的话在多线程下就会发生幻读的情况,而且jdk1.5以后,synchronize的效率已经提升过了吧,性能上和lock类已经差不多了,只不过lock类还有些特殊的用法罢了。
|
|
返回顶楼 | |
发表时间:2011-03-01
最后修改:2011-03-01
windrain453 写道 楼主对A class is thread-safe if it behaves correctly when accessed from multiple threads的解释非常误导人。 该解释不是我写的,是jdk并发包的作者做的解释 只是我没有将"behaves correctly"的解释没有摘录下来,原因在之前回复的帖子中已经说明了 下文是关于"behaves correctly"的一个解释: Correctness means that a class conforms to its specification. A good specification defines invariants constraining an object's state and postconditions describing the effects of its operations. Since we often don't write adequate specifications for our classes, how can we possibly know they are correct? We can't, but that doesn't stop us from using them anyway once we've convinced ourselves that "the code works". This "code confidence" is about as close as many of us get to correctness, so let's just assume that single-threaded correctness is something that "we know it when we see it". Having optimistically defined "correctness" as something that can be recognized, we can now define thread safety in a somewhat less circular way: a class is thread-safe when it continues to behave correctly when accessed from multiple threads. 如果根据该描述,没错,Vector是线程安全的 windrain453 写道 vector是线程安全的,他的方法是同步的,但如果你自己不保证自己的逻辑是线程安全的,那有什么办法。毕竟那些写api的人没法预测你的所有的业务逻辑。 这点倒是说得很对,jdk中提供的某些类:如ConcurrentHashMap之类的,他们都是根据一些常用的场景来制定的锁策略 但在实践中,我们是要根据自己的业务逻辑,来制定自己模块的锁策略,然后根据自己的锁策略,来使用jdk中的类,而不是传说某个类是线程安全的,就盲目去用 |
|
返回顶楼 | |