I want to keep my user informed of the progress of an I/O operation. At the moment I've got an inner class that I kick off before I start my I/O and stop after it's done. It looks like this:
class ProgressUpdater implements Runnable {
private Thread thread;
private long last = 0;
private boolean update = true;
private long size;
public ProgressUpdater(long size) {
this.size = size;
thread = new Thread(this);
}
@Override
public void run() {
while (update) {
if (position > last) {
last = position;
double progress = (double) position / (double) size * 100d;
parent.setProgress((int) progress);
}
}
}
public void start() {
thread.start();
}
public void stop() {
update = false;
parent.setProgress(100);
}
}
parent
is my reference to my UI and position
is a field in my outer class that represents how far in the I/O we have progressed. I set progress to 100% when stopping because sometimes the I/O finishes and stops my updater before it can finish updating the previous increment. That just ensures it's at 100%.
At the moment, this works, and I use it like this:
ProgressUpdater updater = new ProgressUpdater(file.length());
updater.start();
//do I/O
//...
updater.stop();
The problem is that the loop eats CPU pretty badly. I tried throwing a lock (with a wait/notify) in there but I don't know what I'm doing when it comes to using wait/notify so it just hung my thread. What can I do to stop it from using so many CPU cycles?