G
Gast
Gast
Hi,
ich habe eine Frage zum standard Thread-Beispiel Erzeuger-Verbraucher.
Ausgangscode:
Dieser soll nun Threadsicher gemacht werden.
Ich stoße im Internet immer auf folgendes:
Ich selber hatte mir davor folgendes überlegt:
Funktioniert meine Methode auch, oder habe ich irgendetwas nicht beachtet?
ich habe eine Frage zum standard Thread-Beispiel Erzeuger-Verbraucher.
Ausgangscode:
Code:
public class Buffer {
private boolean empty = true;
private Data value = null;
public void put(Data d){
value = d;
emptry = false;
}
public Data get(){
Data d = value;
value = null;
empty = true;
return d;
}
}
Dieser soll nun Threadsicher gemacht werden.
Ich stoße im Internet immer auf folgendes:
Code:
public synchronized void put(Data d) {
while (!empty) {
try {
wait();
}
catch (InterruptedException e) {}
}
value = d;
empty = false;
notify();
}
public synchonized Data get() {
Data d;
while (empty) {
try {
wait();
}
catch (InterruptedException e) {}
}
d = value;
value = null;
empty = true;
notify();
return d;
}
Ich selber hatte mir davor folgendes überlegt:
Code:
public synchronized void put(Data d) {
while (!empty)
notify();
value = d;
empty = false;
}
public synchonized Data get() {
Data d;
while (empty)
try {
wait();
}
catch (InterruptedException e) {}
d = value;
value = null;
empty = true;
return d;
}
Funktioniert meine Methode auch, oder habe ich irgendetwas nicht beachtet?