阅读背景:

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

来源:互联网 

Here is the code:

这是代码:

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, b = 2");
        } else {
            System.out.println("Thread[" + Thread.currentThread().getName() + "] b=" + b + ";a=" + a);
        }
    }

    public static void main(String[] args) {
        // create many many threads
        while (true) {
            // create test every time, to make sure a is 1 and b is 2 again
            final ThreadCacheSample test = new ThreadCacheSample();

            // one thread for changing
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    test.change();
                }
            }).start();

            // one thread for printing
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    test.print();
                }
            }).start();

        }
    }
}    
public class Thread



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: