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
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); } } }
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"); } } }