当我从ThreadMain类中删除df.calculateFreq()时,此代码会产生连续的声音。当我把它放在genTone()方法下面时,控制台打印出" test"只有一次然后停止而没有它代码工作正常。它没有足够的时间来处理额外的数据吗?谢谢,代码没有错误。
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);
}
}
答案 0 :(得分:3)
ScheduledExecutor可能会默默地抛出错误,并终止线程 - 这确实发生了。
将tryTone()方法的内容包装在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();
}
}