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: get start
set start
set end
set start
set end
pool-1-thread-1: z is 0
pool-1-thread-1: x is 2
pool-1-thread-1: y 是 2
pool-1-thread-1: 结束
预期输出: pool-1-thread-1: get start set start
set end
set start
set end
pool-1-thread-1: z is 2
pool-1-thread-1: x is 2
pool-1-thread-1 : y 是 2
pool-1-thread-1: 结束
为什么输出不显示带有 volatile 关键字的 z 的更新值。