使用易失性变量和信号量-Java [英] Using volatile variables and semaphores - Java

查看:89
本文介绍了使用易失性变量和信号量-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从线程,信号量,易失性变量等开始. 我想知道是否在使用信号量时是否有必要将变量定义为volatile,我的意思是:

I'm starting with Threads, Semaphores, volatile variables, etc. I wonder if when I'm using Semaphores it is necessary to define the variable as volatile, I mean:

例如,具有2个线程,一个增加,另一个减少变量,显然,在每次访问之前,我都有一个互斥量,该互斥量可以随时控制只有一个线程在使用该变量.

Having 2 Threads, one increases and the other decreases the variable for example and obviously, before each access I have a mutex that controls at any time only one thread is "playing" with the variable.

是否有必要将其定义为易失性?

It would be necessary to define as volatile?

推荐答案

来自

内存一致性影响:在调用a之前在线程中执行的操作 释放"方法,例如release() happen-before 之后的动作 成功的获取"方法,例如另一个线程中的acquire().

Memory consistency effects: Actions in a thread prior to calling a "release" method such as release() happen-before actions following a successful "acquire" method such as acquire() in another thread.

因此,可以安全地读取/写入受信号量保护的变量.

So it is safe to read/write variables that are guarded by a semaphore.

这篇关于使用易失性变量和信号量-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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