本文介绍了实例字段的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您的变量没有被多个线程修改,请不要使用任何内容
如果变量引用在创建后没有更改,请使用final
如果您的变量被单线程修改并被其他线程访问,请使用volatile
如果您的变量被多个线程修改并访问:
一种.如果您的操作是原子操作-单步交易,请使用AtomicXXX
b.使用synchronized或锁定如果要保护代码块,请使用API
If your variables are not modified by multiple threads, don't use anything
If your variable reference does not change after creation, use final
If your variable is modified by single thread and accessed by other threads, use volatile
If your variables are modified and accessed by multiple threads:
a. Use AtomicXXX if your operations are Atomic - single step transaction
b. Use synchronized or Lock API if you have a code block to be guarded
在为线程安全项目编程时,如何确定哪个字段应该是线程安全的.例如,我们在多线程项目中的一个名为TestThreadSafe的项目中有一个类.
when programming for a thread safe project, how to determine which field should be thread safe. for example we have a class in a project called TestThreadSafe in a multithread project.
public class TestThreadSafe { public AtomicLong pCounter = new AtomicLong(); public AtomicLong mCounter = new AtomicLong(); protected final ConcurrentMap<K, V> Map = new ConcurrentHashMap<K, V>(); private ScheduledExecutorService ses; private String dir; }在这里,为什么不将ses和dir定义为final或volatile字段?
Here, why do not define ses and dir as final or volatile fields?
推荐答案主要说明:
您可以在此处
有关SE的问题:
atomic/volatile/有什么区别同步了吗?
线程安全"代码?
更多推荐
实例字段的线程安全
发布评论