I want to dispatch a task on a new thread, and I want this task to notify the parent thread during its various stages of execution. Something like shown below:
void unzip(Path source, Path destination, ObserverThread observer) {
int n = compute number of entries;
observer.notify("n: " + n);
while (there are more entries) {
observer.notify("Unzipping " + name of entry);
unzip the entry;
}
observer.notify("done");
}
What will be the standard-library-only solution for this use case? (I want to external dependencies.)
If you're using this in Swing then you should use SwingWorker (part of Java). There's an example on how to publish interim results while doing work in the background.
If you're not using Swing then standard java comes with Executors class. You can create a single thread ExecutorService and submit your Runnable to it. It does not offer a way of publishing results in progress but you can still do callbacks manually like you show in the example.