나는 동시 프로그래밍의 초보자이며, 내가 왜 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