alex czernenk alex czernenk - 5 months ago 8
Java Question

Schedule fixed rate refusing to work

This code produces a continious sound and works when I remove the df.calculateFreq() from the ThreadMain class. When I put it in the genTone() method below the console prints the "test" only once and then stops while without it the code works fine. Does it not have enough time to process the extra data?? Thanks and there is no errors from the code.

public ThreadMain() {
audio = new AudioGenerator(10000);
audio.createPlayer();

dF = new DetermineFreq();

exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//RUN FUNC every 20 millisecond
genTone();

}
}, 0, 50, TimeUnit.MILLISECONDS);
}

public void genTone(){
System.out.println("test");
dF.calculateFreq(); <--- this
tone = audio.getSineWave(noteDuration, 10000, 200);
audio.writeSound(tone);
}





public class DetermineFreq{
MainActivity main;

float accelX;

public void DetermineFreq() {
main = new MainActivity();
}

public void calculateFreq() {
accelX = main.getAccelX();
System.out.println(accelX);
}
}

Answer

The ScheduledExecutor may be silently throwing an error, and terminating the thread- this does happen.

Wrap the contents of your genTone() method in a try catch and print the stack trace of any exceptions caught.

public void genTone(){
    try
        {
        System.out.println("test");
        dF.calculateFreq();
        tone = audio.getSineWave(noteDuration, 10000, 200);
        audio.writeSound(tone);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}