I have a little problem, now I have to work on a small Java project. I’m trying to run a few threads from Button event handler; then the last one of the threads must update TextArea on the UI. The threads are doing computational stuff work. The most important part is to make the UI woks fine – I don’t want to freeze the UI and of course I want to update the UI’s TextArea from one of the other threads at regular intervals (not the ui’s one). So here is a part of my code:
Inside Button’s the event handler I’m starting these 4 threads:
Thread generate = new CombinaMaker();
generate.run();
Thread forward = new TranslateForward();
forward.run();
Thread backward = new TranslateBackward();
backward.run();
Thread refresh = new Refresher();
refresh.run();
I want the threads to work simultaneously. The Refresher thread must update the UI TextArea component at regular intervals.
So, here is how I update the UI from Refresher thread:
public static void updateProgress()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
//HERE
//I have a loop that have to be looping at every 500 ms
}
}
}
My qustion is: am I supposed to do that link this? I need to be simple and effective. This loop is making me sad because it must be looping as long as the application works. May be this is the reason of freezing the UI? I know that I am making big error somewhere, but at this moment I can’t find it alone. May be you can suggest me some simple solution. And the last think – the first 4 threads: I want to start them ‘simultaneously’, without freezing my UI. Is that way (starting them like this from the event handler…) the correct one or may be there is better? Thanks a lot friends!
PS. If the refreshing the UI through my ‘refresher’ thread is hard work I am ready for a compromise variant – Update the UI through his owns thread (UI thread). But in this case may be I must use some ‘time shooting mechanism’ – avoiding the freezing of the UI. What are you thinking?
The main problem is your algorithm. Instead of
You should have
i.e.
The runnable passed to
SwingUtilities.invokeLater()is executed in the event dispatch thread. It must not execute long-running tasks. Looping endlessly is a very long running task.