可以证明“易失性”的代码示例,声明应该使用 [英] The code example which can prove "volatile" declare should be used

查看:161
本文介绍了可以证明“易失性”的代码示例,声明应该使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我不明白我们应该使用 volatile 来声明变量。



研究和搜索一些材料很长时间,并知道,当一个字段被声明为易失性,编译器和运行时注意到这个变量是共享的,并且对它的操作不应该与其他内存操作重新排序。 p>

然而,我仍然不能理解在什么情况下应该使用它。我的意思是,有人可以提供任何示例代码,可以证明使用volatile带来好处或解决问题相比,而不使用它。

解决方案

p>这里是为什么 volatile 是必要的示例。如果您删除关键字 volatile ,则线程1 可能永远不会终止。 (当我在Linux上对Java 1.6 Hotspot进行测试时,情况确实如此 - 您的结果可能会有所不同,因为JVM没有义务对未标记为 volatile 的变量执行任何缓存。 )

  public class ThreadTest {
volatile boolean running = true;

public void test(){
new Thread(new Runnable(){
public void run(){
int counter = 0;
while (运行){
counter ++;
}
System.out.println(Thread 1 finished。Counted up to+ counter);
}
}开始();
new Thread(new Runnable(){
public void run(){
//睡一会儿,线程1有机会启动
try {
Thread.sleep(100);
} catch(InterruptedException ignored){}
System.out.println(Thread 2 finishing);
running = false;
}
})。start();
}

public static void main(String [] args){
new ThreadTest()。test();
}
}


Currently I can't understand when we should use volatile to declare variable.

I have do some study and searched some materials about it for a long time and know that when a field is declared volatile, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations.

However, I still can't understand in what scenario we should use it. I mean can someone provide any example code which can prove that using "volatile" brings benefit or solve problems compare to without using it?

解决方案

Here is an example of why volatile is necessary. If you remove the keyword volatile, thread 1 may never terminate. (When I tested on Java 1.6 Hotspot on Linux, this was indeed the case - your results may vary as the JVM is not obliged to do any caching of variables not marked volatile.)

public class ThreadTest {
  volatile boolean running = true;

  public void test() {
    new Thread(new Runnable() {
      public void run() {
        int counter = 0;
        while (running) {
          counter++;
        }
        System.out.println("Thread 1 finished. Counted up to " + counter);
      }
    }).start();
    new Thread(new Runnable() {
      public void run() {
        // Sleep for a bit so that thread 1 has a chance to start
        try {
          Thread.sleep(100);
        } catch (InterruptedException ignored) { }
        System.out.println("Thread 2 finishing");
        running = false;
      }
    }).start();
  }

  public static void main(String[] args) {
    new ThreadTest().test();
  }
}

这篇关于可以证明“易失性”的代码示例,声明应该使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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