public class FieldVisibility {
volatile int a = 1;
volatile int b = 2;
// static final Set<ExecutionResult> results = new HashSet<>();
/**
* 四种结果:
* ExecutionResult{a=3, b=2} write1 -> read -> write2
* ExecutionResult{a=3, b=3} write1 -> write2 -> read
* ExecutionResult{a=1, b=2} read -> write1 -> write2
* ExecutionResult{a=1, b=3} 发生可见性问题
*
* 解决可见性问题可以使用volatile关键字,修饰之后运行结果:
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<50000;i++) {
FieldVisibility fieldVisibility = new FieldVisibility();
Thread thread1 = new Thread(() -> {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
fieldVisibility.change();
});
Thread thread2 = new Thread(() -> {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
fieldVisibility.print();
});
thread1.start();
thread2.start();
// thread1.join();
// thread2.join();
}
// for(ExecutionResult result : results) {
// System.out.println(result.toString());
// }
}
public void change() {
a = 3;
b = a;
}
public void print() {
// results.add(new ExecutionResult(a, b));
System.out.println("a=" + a + "; b=" + b);
}
}
救命,老师,同学们!
登录后可查看更多问答,登录/注册