首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >java中的易失性问题

java中的易失性问题
EN

Stack Overflow用户
提问于 2015-07-27 22:19:04
回答 1查看 80关注 0票数 0

我正在尝试理解volatile在java中是如何工作的。下面是我尝试过的简单程序

代码语言:javascript
复制
public class ThreadTryTry extends Thread {

    static InstanceClass iCLass = null;

    public static void main(String args[]) throws InterruptedException {
        ThreadTryTry tt1 = new ThreadTryTry();
        ThreadTryTry tt2 = new ThreadTryTry();
        tt1.setName("thread 1");
        tt2.setName("thread 2");
        iCLass = new InstanceClass();
        tt1.start();

        // Thread.sleep(1000);
        tt2.start();

        // Thread.sleep(1000);
        iCLass.display();
    }

    public void run() {
        System.out.println("x= " + iCLass.x + " " + Thread.currentThread().getName());
        System.out.println("y= " + iCLass.y + " " + Thread.currentThread().getName());
        iCLass.x++;
        iCLass.y++;
    }  
}

class InstanceClass {

    volatile int x = 0;
    volatile int y = 0;

    public void display() {
        System.out.println("x= " + x + " y= " + y);
    }
}

输出结果与预期一致

代码语言:javascript
复制
x= 0 thread 1
y= 0 thread 1
x= 1 thread 2
y= 1 thread 2
x= 2 y= 2

如果我删除睡眠语句,我会得到如下的随机输出

代码语言:javascript
复制
x= 0 y= 0
x= 0 thread 2
y= 0 thread 2
x= 0 thread 1
y= 1 thread 1

我的期望是,无论线程是否休眠,输出都应该与初始输出相同。

我已经检查了有关易失性的其他问题,但找不到我的程序有什么问题。易失性不能保证变量会被读写回内存,其他线程应该看到变量的最新值。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-27 22:29:34

这里没有问题。

可能会发生什么?

在绝对(和假的)时间线上可能的执行:

代码语言:javascript
复制
t1 starts
t2 starts
main displays
t2 prints x=0
t2 prints y=0
t1 prints x=0
t2 increments x
t2 increments y
t1 prints y=1

main、t1和t2之间没有发生关系,因为它们都是并发的,所以发生的顺序可能会有所不同。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31655649

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档