Java volatile并发

编程入门 行业动态 更新时间:2024-10-26 13:32:25
本文介绍了Java volatile并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好,所以我只读了这个问题您使用过吗Java中的volatile关键字?,我开始使用volatile变量来停止循环。我也看到了这个参考, www.javamex/tutorials/synchronization_volatile。 shtml 。现在,文章说易失性变量是非阻塞的。它还说,它不能用于读取-更新-写入序列中的并发。这是有道理的,因为它们不受阻碍。

Ok so I just read this question Do you ever use the volatile keyword in Java?, and I get using a volatile variable in order to stop a loop. Also I've seen this reference, www.javamex/tutorials/synchronization_volatile.shtml. Now the article says that volatile variables are non-blocking. Also it says that it cannot be used for concurrency in a read-update-write sequence. Which makes sense because they're non-blocking.

由于从不缓存volatile变量,仅使用同步来停止循环(从较早的链接开始)是否更快?

Since volatile variables are never cached is it faster to simply use synchronization to stop the loop (from the earlier link)?

编辑:使用同步解决方案

Using a synchronized solution

public class A{ private boolean test; public A(){ test = true; } public synchronized void stop(){ test = false; } public synchronized boolean isTrue(){ return test; } } public class B extends Thread { private A a; public B(A refA){ a = refA; } public void run(){ //Does stuff here try{ sleep(1000); } catch(Exception e){} a.stop(); } public static void main(String [] args){ A TestA = new A(); B TestB = new B(TestA); TestB.start(); while(TestA.isTrue()){ //stay in loop System.out.println("still in loop"); } System.out.println("Done with loop"); } }

推荐答案

否,读取 volatile 变量比读取 synchronized的非 volatile 变量要快。 块。

No, reading a volatile variable is faster than than reading an non-volatile variable in a synchronized block.

A 已同步块清除条目上的缓存值,这是相同的读取 volatile 变量。 但是,还会在退出同步块时将所有缓存的写操作刷新到主内存中,这在读取 volatile 变量时不是必需的。

A synchronized block clears the cached values on entry which is the same as reading a volatile variable. But, it also flushes any cached writes to main memory when the synchronized block is exited, which isn't necessary when reading volatile variable.

更多推荐

Java volatile并发

本文发布于:2023-11-12 16:58:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582033.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java   volatile

发布评论

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

>www.elefans.com

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