1 Time critical thread and many low priority threads - time critical being slowed
I'm attempting to create a game with (obviously) a main game loop and also several threads doing work that can be finished 'whenever'; getting new game content ready and such. However, despite setting the secondary threads as Minimum Priority they are still slowing down the main thread. The below is code which exibits the behaviour in the bare minimum code.
This code runs at below the requested 60 fps (sometimes as low as 21fps) and occassionally freezes the main thread
If I uncomment the Thread.yield() section it behaves correctly, with the secondary threads using whatever spare processor time is available. However, netbeans produces a warning saying this is basically very unwise. So what is the correct way to get the behaviour I want: 1 thread taking as much processor as it wants with secondary threads taking whatevers left.
Thanks for any advice
Code :
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
long count=0;
int fps=60;
long startTime;
int noOfTimeWasters=50;
ArrayList <Subsidurary> timeWasters=new ArrayList <Subsidurary>();
for(int i=0;i<noOfTimeWasters;i++){
Subsidurary newSub=new Subsidurary();
newSub.t.start();
timeWasters.add(newSub);
}
startTime=System.nanoTime();
while(true){
count++;
long time=System.nanoTime();
try {
Thread.sleep(1000/fps); //I have used Thread.sleep to simulate a jmonkeyengine simpleUpdate call
} catch (InterruptedException ex) {
}
double expendedSeconds=((time-startTime)/(1000d*1000d*1000d));
int actualFPS=(int)(count/expendedSeconds);
System.out.println("" + actualFPS);
}
}
}
Code :
public class Subsidurary implements Runnable{
Thread t;
public Subsidurary(){
t=new Thread(this,"Subsidurary");
t.setPriority(Thread.MIN_PRIORITY);
}
@Override
public void run() {
while(true){
for(int i=0;i<10000000;i++){
double b=Math.sqrt(i);
b=Math.sin(b);
b=Math.cos(b);
b=Math.pow(b, 2);
/*if (i%1000==0){
Thread.yield();
}*/
}
System.out.println("SubCompleted");
}
}
}
Re: 1 Time critical thread and many low priority threads - time critical being slowed
Sounds like you could benefit a lot from Executors and Thread pools.
Also, you're starting 50 threads. The ideal number usually is closer to the number of physical cores your computer has (say no more than 2x the number of available cores). There are exceptions, but these applications are more focused on the other benefits of multi-threading rather than computational performance.
Re: 1 Time critical thread and many low priority threads - time critical being slowed
Thanks; that thread pool sounds very like something I was considering creating manually to manage the problem so thank you for pointing me to it