enum State {
WAITING,
CONSUMING,
SHOULD_STOP_CONSUMING,
FINISHED,
ERROR
}
/** *CreateaStreamConsumer,willbeimmediatelyreadytostartconsuming.
*/ public StreamConsumer() {
output = new ArrayList<String>();
workToBeDone = new Semaphore(0);
outputIsReady = new Semaphore(0);
/** *ExecutorshouldcallthistogetthecapturedoutputofthisStreamConsumer.
*/ public List<String> getOutput() {
try { // Wait until the output is ready.
outputIsReady.acquire();
} catch (InterruptedException e) {
Log.error("Client of StreamConsumer was interrupted while waiting for output?"); returnnull;
}
// Take a copy of the Strings, so when we call output.clear(), we don't // clear the ExecutionResult's list.
List<String> copy = new ArrayList<String>(output); return copy;
}
// Tell Consumer there is work to be done (it will check first if FINISHED has been set.)
workToBeDone.release();
}
privatevoid consume() { try {
if (checkState(State.SHOULD_STOP_CONSUMING)) { // Caller already called processFinished() before we even started // consuming. Just get what we can and finish. while (reader.ready()) {
output.add(reader.readLine());
}
} else { // Caller's process is still executing, so just loop and consume. while (checkState(State.CONSUMING)) { Thread.sleep(50); while (reader.ready()) {
output.add(reader.readLine());
}
}
}
if (checkState(State.SHOULD_STOP_CONSUMING)) {
changeState(State.WAITING, State.SHOULD_STOP_CONSUMING);
} else {
Log.error("StreamConsumer stopped consuming, but was not told to?");
setErrorState();
}
// Tell client of Consumer that the output is ready.
outputIsReady.release();
}
@Override publicvoid run() { while (checkState(State.WAITING)) { try { // Wait until there is work to be done
workToBeDone.acquire();
} catch (InterruptedException e) {
Log.error("StreamConsumer caught InterruptedException while waiting for work");
setErrorState(); break;
}
// Check first if we're done if (checkState(State.FINISHED)) { break;
}
// Make sure we're either supposed to be consuming // or supposed to be finishing up consuming if (!(checkState(State.CONSUMING) || checkState(State.SHOULD_STOP_CONSUMING))) {
Log.error("invalid state: StreamConsumer told about work, but not CONSUMING?");
Log.error("state was: " + getCurrentState());
setErrorState(); break;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.