-2

重複の可能性:
静的グローバル変数と静的揮発変数の違いは何ですか?

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();
}
}

static 変数と volatile 変数の違いがわかりませんでしたか?

上記のコードでは、静的変数でも同じことを達成できますが、揮発性のみが目的を果たす例を教えてもらえますか?

4

1 に答える 1

0

最初に頭に浮かんだのは:

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

値に volatile を使用して、更新の原子性を強制します。

于 2013-01-06T08:28:22.787 に答える