java变量即使不使用volatile也是可见的

时间:2018-05-02 19:22:41

标签: java multithreading volatile

我正在尝试理解java volatile,我的理解是在附加的代码中,Reader线程有可能看不到对sharedData进行的Writer线程更新,因为计数器变量不是声明为volatile。但是在多次运行中,我已经看到WriterThread的更改对ReaderThread立即可见,即使我没有将volatile与counter变量一起使用。有人可以指出我出错的地方吗?

public class App 
{
    public static void main( String[] args )
    {
        SharedData sharedData = new SharedData();

        new WriterThread(sharedData, "Writer1").start();;

        new ReaderThread(sharedData, "Reader1").start();;
    }
}


class SharedData{
    public int counter=0;
}


class ReaderThread extends Thread{

    private SharedData sharedData;
    ReaderThread(SharedData sd , String name){
        super(name);
        this.sharedData = sd;
    }
    public void run() {
        while(true) {
        System.out.println(this.getName() + ": " + sharedData.counter);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    }

}

class WriterThread extends Thread{

    private SharedData sharedData;
    WriterThread(SharedData sd , String name){
        super(name);
        this.sharedData = sd;
    }
    public void run() {
        while(true) {
        System.out.println(this.getName() + ": " + ++sharedData.counter);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }

    }

} 

0 个答案:

没有答案