私は並行プログラミングの初心者です。私はsleep(1)
で にコメントしたときにこのプログラムが終了しない理由を正確に理解したいと思います。 )Main
スレッドに戻って手を差し伸べます。おそらく、Busy waitingと何か関係がありますか?並行プログラミング、スレッド間で値を共有
public class Rdv<V> {
private V value;
public void set(V value) {
Objects.requireNonNull(value);
this.value = value;
}
public V get() throws InterruptedException {
while(value == null) {
Thread.sleep(1); // then comment this line !
}
return value;
}
public static void main(String[] args) throws InterruptedException {
Rdv<String> rendezVous = new Rdv<>();
new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
rendezVous.set("hello");
}).start();
System.out.println(rendezVous.get());
}
}
関連:https://stackoverflow.com/questions/42676751/thread-sleep-makes-compiler-read-value-every-time – shmosel