Java线程-同步问题

标签 java multithreading synchronization

来自 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/

相关文章:

java - Tomcat context.xml 的 Netbeans 问题

c++ - 从不同线程同步访问和删除列表中的项目。

python - 线程应用程序的信号量同步失败,Python

ios - ALAssetsLibraryassetForURL 方法的同步问题

android - 使用 Sqlite 下载并上传到同步数据库 MySql

java - 在 Android Gradle 插件版本 8.0 中,资源 ID 默认不是最终的,请避免在 switch case 语句中使用它们

java - 配置 Hibernate 以适应现有的数据库约束?

java - 有 OOP 委托(delegate)时选择类方法

java - 在惰性初始化供应商中引用 "this"?

使用 kbhit 的 Python 套接字线程