请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

老师,关于可见性的问题

我的代码并没有使用Volatile和Synchronized关键字保证可见性,为啥还是有可见性呢??

public class SynchronizedClass {
    private int value = 100;

    public static void main(String[] args) throws InterruptedException {
        SynchronizedClass s = new SynchronizedClass();
        SynchronizedThread synchronizedThread = new SynchronizedThread(s);
        Thread t = new Thread(synchronizedThread);
        SynchronizedThread2 synchronizedThread2 = new SynchronizedThread2(s);
        Thread t2 = new Thread(synchronizedThread2);
        t.start();
        t2.start();
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}

class SynchronizedThread implements Runnable {
    private SynchronizedClass obj;

    public SynchronizedThread(SynchronizedClass obj) {
        this.obj = obj;
    }

    @Override
    public void run() {
        while (obj.getValue() == 100) {

        }
        System.out.println("end");
    }
}

class SynchronizedThread2 implements Runnable {
    private SynchronizedClass obj;

    public SynchronizedThread2(SynchronizedClass obj) {
        this.obj = obj;
    }

    @Override
    public void run() {
        obj.setValue(200);
        int i = 0;
        while (true) {
            i++;
        }
    }
}

正在回答 回答被采纳积分+3

1回答

悟空 2025-01-21 16:43:05
不使用关键字的时候,程序也会尽力,但是不保证能完全可见
0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号