2013-01-06 75 views
-2

可能重复的:
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变量之间的区别?

在上面的代码中我也可以用静态变量来实现同样的事情,任何一个身体只给我例子只有volatile才能达到目的?

回答

相关问题