Multithreaded CPU load on Windows
Hi,
I'm trying to determine whether my Pentium D running 32bit Windows XP is load-balancing between the two CPU cores correctly. To do this I'm running the following small test app. (It's a complete app and should compile for anyone)
import java.text.DecimalFormat;
import java.util.Random;
/**
* I am interested in finding out if the Windows implementation of the Sun
* JVM will multithread on a dual processor. I have a Pentium D at home and
* I'm not always convinced that it load-balances very well. Let's see if
* it offers an advantage when using Java to write a multithreaded program.
*
* @author Gordon
* @version 20070421 Initial Creation
*/
publicclass MultiThread{
publicstaticfinalint NUM_THREADS = 1000;
publicstaticfinal DecimalFormat FORMATTER =new DecimalFormat("0000");
public MultiThread(){
super();
}
/**
* @param args
*/
publicstaticvoid main(String[] args){
for(int i = 0; i < NUM_THREADS; i++){
Thread t =new Thread(new Thrash(),"Thread" + FORMATTER.format(i));
t.setPriority(Thread.MAX_PRIORITY);
t.start();
synchronized(System.out){
try{
System.out.wait(10);
}
catch(InterruptedException ex){
System.out.notifyAll();
}
}
}
}
/**
* Define a Runnable that does something fairly heavy, but that will complete of
* its own accord eventually.
*/
publicstaticclass Thrashimplements Runnable{
private Random _rand =null;
public Thrash(){
_rand =new Random(System.currentTimeMillis());
}
publicvoid run(){
int i = 0;
while(i < 1000){
int r = _rand.nextInt(10);
i += r;
synchronized (System.out){
System.out.println(Thread.currentThread().getName() +" i = " + i);
r *= r;
try{
// give other threads a chance to get going
System.out.wait(25);
}
catch(InterruptedException ex){
System.out.notifyAll();
}
}
}
}
}
}
The code is compiled with JDK1.5.0_11.
Running from a command prompt seems to load both processors fairly evenly if I allow standard out to stream to the console. But if I pipe output to a text file then only CPU 1 seems to have any load. I suspect this is the truer image of what's going on and the even load in the first case is as much Windows struggling to keep up with the output.
Is the Windows implementation of the 1.5 JVM multithreaded across dual core CPUs? Should I expect to see an evenly spread load for my example program? Have I misunderstood something and my program is wrong. (A race condition I'm missing? Not a heavy enough load to force it onto the second procesosr?)
Thanks in advance...
Gordon

