实例字段的线程安全

编程入门 行业动态 更新时间:2024-10-28 05:15:56
本文介绍了实例字段的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

推荐答案

主要说明:

  • 如果您的变量没有被多个线程修改,请不要使用任何内容
  • 如果变量引用在创建后没有更改,请使用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
  • 您可以在此处

    有关SE的问题:

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

    线程安全"代码?

    更多推荐

    实例字段的线程安全

    本文发布于:2023-08-04 23:03:59,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1300372.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:字段   线程   实例

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!