小编shr*_*van的帖子

vola关键字无法正常使用

无论有没有volatile关键字,我都会得到相同的输出。

我在代码中犯了错误吗?

public class MutliThreadExample extends Thread{

    volatile int value;
    
    public static void main(String[] args) throws InterruptedException {
        MutliThreadExample thread1 = new MutliThreadExample();
        MutliThreadExample thread2 = new MutliThreadExample();
        thread1.start();
        thread1.join();
        thread2.start();
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            value = value + 1;
            System.out.println(value + "-" + Thread.currentThread());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

我无法volatile在 Java 中正确使用关键字。

java volatile java-threads

3
推荐指数
1
解决办法
99
查看次数

标签 统计

java ×1

java-threads ×1

volatile ×1