Hi - I have a slight issue with threads. I'm also new to Java so
bear with me if I've done anything stupid!
There are two main classes: Main and FxThread.
FxThread extends Thread and implements Runnable and Main creates three
threads, gets them to run and sticks them in an array with the threads
running in a "while true" loop.
Now, the code all works, but it eats the CPU like there is no tomorrow.
CPU usage actually shoots up to 100% when I run it.
Why is this?
Any help would be much appreciated. Thanks in advance!
------------------------------
public class FxThread extends Thread implements Runnable{
String data;
FxThread(){
data = "this is some data";
}
public void run(){
int i = 0;
while (true)
{
i++;
}
}
}
------------------------------------
public static void main (String [] args)
{
FxThread [] array = new FxThread[3];
FxThread thread = new FxThread();
FxThread thread1 = new FxThread();
FxThread thread2 = new FxThread();
thread.start();
array[0] = thread;
thread1.start();
array[1] = thread1;
thread2.start();
array[2] = thread2;
}
-------------
Thomas Weidenfeller - 29 Apr 2005 12:33 GMT
> Hi - I have a slight issue with threads. I'm also new to Java so
> bear with me if I've done anything stupid!
comp.lang.java.help is the next door to the right.
> Now, the code all works, but it eats the CPU like there is no tomorrow.
> CPU usage actually shoots up to 100% when I run it.
That is exactly what you have programmed.
> public void run(){
> int i = 0;
[quoted text clipped - 4 lines]
> }
> }
Here you burn all your CPU cycles. This endless loop runs, and runs, and
runs, and uses CPU time. What else do you expect?
/Thomas

Signature
The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
"." - 29 Apr 2005 20:10 GMT
> Hi - I have a slight issue with threads. I'm also new to Java so
> bear with me if I've done anything stupid!
[quoted text clipped - 9 lines]
>
> Why is this?
The code in FxThread.run() is pretty straight forward. It does not have to
wait on anything except the CPU. Programs that run at less than 100% CPU
are usually waiting for network access, hard drive access, a lock on a
resource, etc.
If you want to slow the threads down they will either have to try
accessing resources shared by others (thus they will have to wait for
those resources) or you can just add a Thread.sleep(milliseconds); in the
code to make it pause for a few milliseconds every iteration.
> Any help would be much appreciated. Thanks in advance!
>
[quoted text clipped - 12 lines]
> {
> i++;
Thread.sleep(1000); // sleep for a second
> }
> }
[quoted text clipped - 19 lines]
> }
> -------------

Signature
Send e-mail to: darrell dot grainger at utoronto dot ca