Heavy math routines and separate threads?
I have a number of heavy math/cpu usage routines and gather it would be good to make them separate threads so things like JProgressBar and other stuff will work correctly.
Is this all I need to do to make them runnable in their own threads?
final Runnable HM = new Runnable()
{
public void run()
{
heavy_math(x, y, z);
}
};
Is there a general method I could call before and after a heavy math routine that would do the same thing?
Is it possible that the threads will get out of sync?
I haven't gotten a handle on this thread stuff yet so I must ask dumb questions.
RON C
1 Attachment(s)
meisl, there is a bit more on deprecated Thread methods here:
Quote:
Maybe it's a bit short there. But there's the lang-spec and the spec of the JVM as well
See the attatched copy from the java doc
1 Attachment(s)
little demo to play around with
Hey Ron,
I have put together a little demo that uses various threads, two of them doing "heavy math stuff". The progress of these two is displayed via JProgressBars and there are buttons to start, stop, suspend, resume one or both. On STDOUT it prints messages about what happens including information in which thread something happened.
The methods stop(), suspend() and resume() in class HeavyMathCalculator implement the suggested patterns while avoiding Thread.stop(), Thread.suspend() and Thread.resume().
I'm sorry that all is quite complicated, but maybe you can nonetheless adapt it for your purpose. It's grown out of size mostly because of those bloody buttons, that you would not need in your app I guess.
In any case, I'd like to recommend the chapters on Threads and Progress Bars in the Java Tutorial, that may be easier to understand than the technical papers, including the javadoc on Thread primitive deprecation.
There is a built-in test in this demo:
After it has started, click the following buttons:
1. "start/resume both"
2. "math1.stop()"
3. "suspend both"
4. "math1.resume()"
What is going on here?! Can you repair this?
Well, maybe I should add that in fact there is a general flaw in my conceptual design of the buttons... :o
Anyways, have fun with it.
p.s.: I'm still interested in what your heavy math stuff is calculating.
meisl, just out of curiosity...
Can't this:
Thread.sleep( 10 + new Random().nextInt(100) ); // give other threads time to do their work
be replaced with this:
Thread.currentThread().yield();
at strategic places in the heavy math code, - or nothing to halt it at all, -
just threads running with normal priority ?
As it is now, the sleeping is there just to show the progressbars progressing...
And why must the GUI be made by a new thread, what is wrong with
just makeing the GUI - in the programs main thread ?
I did this, with no visible difference to the execution:
Code:
public ThreadProgressDemo(boolean isVerbose) {
this.isVerbose = isVerbose;
createAndShowGUI();
System.out.println("GUI created");
}