我是并发编程的初学者,我想确切地理解为什么当我sleep(1)
在get()
我的第一个想法中评论时这个程序没有结束,是 sleep(1) 将手交还给Main
线程,也许忙等待有有什么关系?
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());
}
}