【问题标题】:Can anybody give me example of using Volatile [duplicate]谁能给我使用 Volatile 的例子 [重复]
【发布时间】:2013-01-06 08:15:57
【问题描述】:

可能重复:
What is the difference between a static global and static volatile variable?

public class Test {
volatile  boolean running = true;

public void count() {
    new Thread(new Runnable() {
        public void run() {
            int counter = 0;
            while (running) {

                counter++;
                System.out.println("Thread 1 counting " + counter);
            }
            System.out.println("Thread 1 finished. Counted up to "
                    + counter);
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {             
            try {
                Thread.sleep(1);
            } catch (InterruptedException ignored) {
            }
            System.out.println("Thread 2 finishing");
            running = false;
        }
    }).start();
}

public static void main(String[] args) {

    new Test().count();
}
}

我没有发现静态变量和易失变量之间的区别?

在上面的代码中,我也可以用静态变量实现同样的目的,任何机构都可以给我举个例子,只有 volatile 才能达到目的吗?

【问题讨论】:

    标签: java static volatile


    【解决方案1】:

    我想到的第一个:

    http://www.docjar.com/html/api/java/util/concurrent/atomic/AtomicLong.java.html

    在值上使用 volatile 来强制更新的原子性。

    【讨论】:

      猜你喜欢
      • 2013-06-06
      • 1970-01-01
      • 2011-02-28
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多