保证线程安全的策略大体可以分为以下几个:
- 不可变对象:对象只能读,不能修改,从根本上消除了多线程的不安全感。
[En]
immutable objects: objects can only be read and cannot be modified, eliminating the insecurity of multithreading from the root.*
- 线程封闭:线程之间不共享变量。
- 同步容器:使用同步关键字修改关键方法,确保对象关键操作的线程安全。
[En]
synchronization container: use synchronization keywords to modify key methods to ensure thread safety of key operations of objects.*
- 并发容器:针对同步容器进行优化。
不可变对象
大多数线程不安全因素是由于多个线程同时修改共享变量而导致的冲突,因此如果将对象设置为不可变,可以避免相当大的麻烦。
[En]
Most thread unsafe factors are due to conflicts caused by multiple threads modifying shared variables at the same time, so a considerable amount of trouble can be avoided if the object is set to immutable.
final
final关键字修饰的对象的值是不能够再被修改的,对于基本数据类型以及String,使用final修饰,就意味着它们再不能被修改。
final修饰的类:不能够被继承,其中的方法也隐式地被final修饰;final修饰的方法:不能被子类重写;final修饰的对象:值不能被修改。
String类是不可变对象中的典范,它只要被初始化之后,就不能再被改变了,其中主要用到了以下的手法:
封装对象