小编son*_*zhw的帖子

为什么关于线程的代码显示a = 1和b = 3?为什么添加"挥发性"不起作用?

这是代码:

public class ThreadCacheSample {
    int a = 1;
    int b = 2;

    public void change() {
        a = 3;
        b = a;
    }

    public void print() {
        if (a == 1 && b == 3) {
            // why this is happening?
            System.out.println("Thread[" + Thread.currentThread().getName() + "]Confused1 : a = 1, b = 3");
        } else if (a == 3 && b == 2) {
            // why this is happening, too?
            System.out.println("Thread[" + Thread.currentThread().getName() + "]Confused2 : a = 3, …
Run Code Online (Sandbox Code Playgroud)

java multithreading atomic volatile thread-safety

2
推荐指数
1
解决办法
62
查看次数

标签 统计

atomic ×1

java ×1

multithreading ×1

thread-safety ×1

volatile ×1