-1
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 的更新值。

4

2 回答 2

0

我猜你正在寻找这样的东西:synchronized在你的方法中使用关键字。这确保了这个方法中的命令都被执行,就好像它只是一个语句一样。因此,在这些语句之间没有发生任何事情。

public synchronized void set() {
    System.out.println("set start");
    x++;
    y++;
    z++;
    System.out.println("set end");
}
于 2018-10-30T07:57:09.097 回答
0

这是因为存在volatile会简单地强制在主内存上读取任何对其执行的原子操作,但z++等效于z = z + 1这意味着那里有两个操作:读取操作和写入操作。多个线程仍然可以在这两个操作之间读取/写入值。

于 2018-10-30T05:36:56.400 回答