교수가 제공 한 책의 시험을 치고 있으며 스레드 및 동기화와 관련된 코드가 있습니다. 상태가 변경 될 때마다 알림을 받고 싶습니다. 상태 변경을 놓치지 않고).notify 및 notifyAll/synchronising 코드 (이해 도움말)
public class C {
private int state = 0; // the state
private boolean modified = false; // to show if the state was changed since actualization
public synchronized void printNewState() {
while (true) {
if (!modified) {
wait();
}
System.out.println(state);
modified = false;
notify();
}
}
public synchronized void setValue(int v) {
if (modified) {
wait();
}
state = v;
notify();
modified = true;
System.out.println("value set");
}
}
그리고이 다음은 writen 것 :
을하지만, (INT)가 printNewState 스레드를 깰 방법의 SetValue는()에서 통지가 보장되지 않습니다! 자바에서 우리가가는 notifyAll (의 도움으로이 문제 를 해결) 조금 바쁜 대기 걸릴 다음 이 통지 이유) (도가는 notifyAll로 변경되지 않았습니다
public synchronized void printNewState() {
while (true) {
while (!modified) {
wait();
}
System.out.println(state);
modified = false;
**notify();** \\(?)
}
}
public synchronized void setValue(int v) {
while (modified) {
wait();
}
state = v;
notifyAll();
modified = true;
System.out.println("value set");
}
이해가 안가? 이 통지가 setValue (int)의 thread에 보내지는 것이 보증되지 않는 경우가 있습니다. ???
는notifyAll()
방법은 모든 대기 스레드를 깨어 반면
notify()
방법은, 하나의 대기 스레드를 깨어 나면 당신
안녕하세요. Grexis, 제가 질문을 편집했습니다. 죄송합니다. 나는 너의 대답 tho에 흥미있다. – ovoxo
@ovoxo, 제 편집 참조. tl; dr은'notifyAll()'대신'notify()'를 쓰는 것이 스레드 업데이트 만 기다리고있는 한 의미가 있습니다. – Grexis
답변 해 주셔서 대단히 감사합니다. :) – ovoxo