【发布时间】:2015-02-26 17:45:59
【问题描述】:
我正在用 Java 编写节奏游戏;现在我已经到了尝试实现节拍器对象的地步。
我编写了一个数据结构,将 8 通道音乐数据存储到单个 QuarterBeat 对象中;这些依次存储在 64 个组中,以制作 4 度量“块”对象。
为了使事情保持正确同步,我想使用一对并行线程:一个运行在每个四分之一节拍发生的各种事件,然后在“wait()”方法上停止,而另一个等待从发出第一个信号之前的 BPM。
这是执行工作的线程的代码。
public class InGame {
public static boolean gameRunning = false;
public static boolean holdChunk = false;
public static boolean waiting = false;
public static ArrayList<Player> players = new ArrayList<Player>();
public void startUp() throws InterruptedException{
Parser.loadSamples();
for (int p = 0; p < Player.voicePool.size(); p++) {
Player makePlay = new Player();
makePlay.setChannel(p);
players.add(makePlay);
}
LevelStructure.SongBuild();
Metro timer = new Metro();
gamePlay(timer);
gameEnd();
}
synchronized public void cycle(Metro timer) throws InterruptedException{
int endPoint = LevelStructure.getChunkTotal();
for (int chunk = 0; chunk < endPoint; chunk++){
LevelStructure.setActiveChunk(chunk);
for (int quartBeat = 0; quartBeat < 64; quartBeat++){
synchronized (this){
new Thread(timer.ticking(this));
Player.getNewNotes(LevelStructure.getQuartBeat(quartBeat));
players.get(0).playback(LevelStructure.getQuartBeat(quartBeat));
waiting = true;
while (waiting) {
wait();
}
}
}
if (holdChunk) chunk--;
}
}
}
以及 Metro 对象的代码:
public class Metro {
public static int BPM;
synchronized public Runnable ticking(InGame parent) throws InterruptedException{
synchronized (parent) {
Thread.sleep(15000/BPM);
InGame.waiting = false;
parent.notifyAll();
}
return null;
}
}
现在每次我尝试运行它时都会抛出 Illegal Monitor State 异常;我已经尝试自己研究 wait()/notify() 的正确实现,但我对 Java 还是很陌生,我找不到我能理解的处理并行线程的解释。我需要从父进程调用 Cycle 和 Metro 线程吗?
编辑:更新代码:现在的问题是,Cycle 对象不是实际并行运行,而是等待 timer.ticking 方法执行,然后在 Metro 休眠时执行它应该执行的操作,然后卡住等待一个永远不会到来的通知。这意味着线程实际上并没有彼此并行执行。
【问题讨论】:
-
一些可能有用的现有线程:stackoverflow.com/questions/886722/…(特别是您收到异常的原因)、stackoverflow.com/questions/3278234/…、stackoverflow.com/questions/8579934/…(有关等待/通知以及何时使用它们的更一般概念/不使用它们)
-
这段代码的线程在哪里?
标签: java multithreading wait notify