当我从ThreadMain类中删除df.calculateFreq()时,此代码会产生连续的声音并起作用。当我将其放在控制台下方的genTone()方法中时,控制台仅打印一次“测试”,然后停止运行,而没有它,代码运行正常。它没有足够的时间来处理额外的数据吗?谢谢,代码没有错误。

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

最佳答案

ScheduledExecutor可能会在无提示的情况下抛出错误,并终止线程,这确实发生了。

将genTone()方法的内容包装在try catch中,并打印捕获到的所有异常的堆栈跟踪。

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

07-27 15:45