实例字段的线程安全 [英] thread safe for instance fields

查看:62
本文介绍了实例字段的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为线程安全项目编程时,如何确定哪个字段应该是线程安全的.例如,我们在多线程项目中的一个名为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?

推荐答案

主要说明:

  1. 如果您的变量没有被多个线程修改,请不要使用任何内容
  2. 如果变量引用在创建后没有更改,请使用final
  3. 如果您的变量被单线程修改并被其他线程访问,请使用volatile
  4. 如果您的变量被多个线程修改并访问: 一种.如果您的操作是原子操作-单步交易,请使用AtomicXXX b.使用synchronized锁定如果要保护代码块,请使用API​​
  1. If your variables are not modified by multiple threads, don't use anything
  2. If your variable reference does not change after creation, use final
  3. If your variable is modified by single thread and accessed by other threads, use volatile
  4. 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

您可以在此处

有关SE的问题:

atomic/volatile/有什么区别同步了吗?

线程安全"代码?

这篇关于实例字段的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆