Java volatile并发 [英] Java volatile for concurrency

查看:71
本文介绍了Java volatile并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我只读了这个问题您使用过吗Java中的volatile关键字?,我开始使用volatile变量来停止循环。我也看到了这个参考, http://www.javamex.com/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, http://www.javamex.com/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并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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