Note that there are some explanatory texts on larger screens.

plurals
  1. POProgress bar updater using up CPU
    text
    copied!<p>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:</p> <pre><code>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 &gt; 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); } } </code></pre> <p><code>parent</code> is my reference to my UI and <code>position</code> 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%.</p> <p>At the moment, this works, and I use it like this:</p> <pre><code>ProgressUpdater updater = new ProgressUpdater(file.length()); updater.start(); //do I/O //... updater.stop(); </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload