1

I'm using a Thread to scroll text in my application :

public void run() {
    super.run();
    while (!isInterrupted()) {

        if (X >= -getPreferredSize().getWidth()) {
            X -= 2;
        } else {

            decrementMessagesInList(getMessages());
            addMessage(getMessages());

            prepare();
            X = getParentWidth();
        }
        try {
            Thread.sleep(50);

        } catch (InterruptedException e) {
            e.printStackTrace();
            break;
        }
        repaint();
    }
}

However, see that with sleep my CPU usage is very high, I need to reduce that. Can anyone suggest how to do it ?

nimda
  • 153
  • 2
  • 8
  • You are telling the components to repaint() every 50ms. If you don't want the CPU usage that high then 1) don't repaint every 50ms, 2) improve your painting logic to make it more efficient. Check out the [Marquee Panel](https://tips4java.wordpress.com/2011/04/24/marquee-panel/) which does text scrolling to see if the CPU usage is any better. – camickr Oct 25 '15 at 17:06

1 Answers1

0

If I can make the assumption that your code only needs to scroll the text in response to some event (say a click or drag or something) then you should make your thread go into a wait state then have the code that triggers the update post a notification over to the thread which will then wake up and do the update. Something like this:

Object syncObj = new Object();

public void run() {
    while (true) {
        try {
            syncObj.wait();
            if (X >= -getPreferredSize().getWidth()) {
                X -= 2;
            } else {
                decrementMessagesInList(getMessages());
                addMessage(getMessages());

                prepare();
                X = getParentWidth();
            }

            repaint();
        } catch (InterruptedException ie) {
            // handle the exception
        }
    }
}

Then in the code which handles/generates the event that causes a need to scroll

public void onClick(..)  {
   syncObj.notifyAll();
}

You also need to guard against spurious wake ups of your thread to make sure the event you were waiting for actually happened. See Do spurious wakeups actually happen?.

Community
  • 1
  • 1
JJF
  • 2,681
  • 2
  • 18
  • 31
  • for clarity, I take text from ArrayList( from parsed XML). the text must be scrolled all the time and code must don't response for events. – nimda Oct 25 '15 at 17:50
  • Do you mean scrolled to the bottom? You only need to run that code when the data in the array list changes. – JJF Oct 25 '15 at 17:56