此代码是否保证打印所有法国 = 巴黎?

问题描述 投票:0回答:1

我对 volatile 提供的保证之前发生的事情有点困惑。我的理解是,一个线程在读取易失性字段之前看到的任何内容都会被随后读取相同易失性字段的另一个线程看到。通过该逻辑,在以下代码中,保证第二个线程可以看到第一个线程放入的键。这样的理解正确吗?

public class Capitals{
    static volatile Map<String, String> capitals = new HashMap<>(); 
    public static void main(String[] args) throws Exception{
        Thread t = new Thread(()->{
                capitals.put("France", "Paris");
            });
        t.start();
        t.join(); //or Thread.sleep(1000);
        new Thread(()->{
                capitals.forEach((a, b)->System.out.println(a+" = "+b));
            }).start();
        }
}

此外,如果大写字段不是易失性,或者如果我使用 Thread.sleep(1000);无法保证第二个线程会打印 France = Paris。对吗?

java multithreading
1个回答
0
投票

是的,你是对的,thread.sleep 正在工作,因为操作很小,主线程可以等待 1000 毫秒,有足够的时间来完成操作。对于易失性来说也是如此,如果线程内部有多个操作,我们将无法获得最新值。

© www.soinside.com 2019 - 2024. All rights reserved.