老师,关于可见性的问题

来源:12-9 概述可见性

张婧仪

2025-01-17

我的代码并没有使用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++;
        }
    }
}
写回答

1回答

悟空

2025-01-21

不使用关键字的时候,程序也会尽力,但是不保证能完全可见
0
0

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程