来自 Sun 的教程:
Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods. (An important exception: final fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is effective, but can present problems with liveness, as we'll see later in this lesson.
Q1。上述语句是否意味着,如果一个类的对象要在多个线程之间共享,那么该类的所有实例方法(最终字段的 getters 除外)都应该同步,因为实例方法流程实例变量?
最佳答案
为了了解 Java 中的并发性,我推荐宝贵的 Java Concurrency in Practice .
针对您的具体问题,虽然同步所有方法是实现线程安全的一种快速而肮脏的方法,但它根本无法很好地扩展。考虑一下备受诟病的 Vector 类。每个方法都是同步的,而且效果很糟糕,因为迭代仍然不是线程安全的。
关于Java线程-同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2760294/