【发布时间】:2018-10-30 05:31:07
【问题描述】:
int x,y;
volatile int z;
public static void main(String[] args) {
ThreadPoolExecutor pool = (ThreadPoolExecutor)Executors.newFixedThreadPool(5);
MainTest mission = new MainTest();
pool.execute(new MissionRead(mission));
pool.execute(new MissionWrite(mission));
pool.execute(new MissionWrite(mission));
pool.shutdown();
}
public void set() {
System.out.println("set start");
x++;
y++;z++;
System.out.println("set end");
}
public void get() {
System.out.println(Thread.currentThread().getName() +": get start");
System.out.println(Thread.currentThread().getName() +": z is " + z);
System.out.println(Thread.currentThread().getName() + ": x is " + x);
System.out.println(Thread.currentThread().getName() +": y is " + y);
System.out.println(Thread.currentThread().getName() +": get end");
}
输出:pool-1-thread-1:开始
设置开始
设置结束
设置开始
设置结束
pool-1-thread-1:z 为 0
pool-1-thread-1: x 是 2
pool-1-thread-1: y 是 2
pool-1-thread-1: 结束
预期输出:pool-1-thread-1:开始
设置开始
设置结束
设置开始
设置结束
pool-1-thread-1:z 为 2
pool-1-thread-1: x 是 2
pool-1-thread-1: y 是 2
pool-1-thread-1: 结束
为什么输出不显示带有 volatile 关键字的 z 的更新值。
【问题讨论】:
标签: java multithreading volatile happens-before