public void print(){
System. out.println( "m:"+m+ ",n:"+n);
}
public static void main(String[] args) {
while( true){
final Volatile v = new Volatile();
new Thread( new Runnable(){
@Override
public void run() {
try {
Thread.sleep( 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
v. set();
}
}).start();
new Thread( new Runnable(){
@Override
public void run() {
try {
Thread.sleep( 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
v.print();
}
}).start();
}
}
}
正常情况下m=0,n=1;m=6,n=6,通过运行我们发现了m=0,n6(需要长时间运行)
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :0, n :1
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :0, n :6
m :6, n :6
m :6, n :6
m :6, n :6
m :0, n :1
m :0, n :1
m :0, n :1
m :6, n :6
m :0, n :1
m :0, n :1
m :0, n :1
m :6, n :6
m :6, n :6
m :6, n :6
m :0, n :1
m :6, n :6
m :6, n :6
package com.swk.thread;
public class Volatile {
private volatile int m = 0;
public void incr(){
m++;
}
public static void main(String[] args) {
final Volatile v = new Volatile();
for( int i= 0;i< 1000;i++){
new Thread( new Runnable(){
@Override
public void run() {
try {
Thread.sleep( 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
v.incr();;
}
public class CheesyCounter {
private volatile int value;
public int getValue() { return value; }
public synchronized int increment() {
return value++;
}
}