我正在用Java写一个节奏游戏;现在我已经达到了我试图实现节拍器对象的程度
我编写了一个数据结构,将8个音乐数据通道存储到一个QuarterBeat对象中;这些又以64个为一组存储,以制作4个量块的“块”。对象。
为了使事物保持正确同步,我想使用一对并行线程:一个贯穿每个四分之一节拍的各种事件,然后停止等待()等待。方法,而另一个方法在发出第一个信号之前等待从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;
}
}
现在每次我试图运行它时都会抛出非法监控状态异常;我已经尝试自己研究wait()/ notify()的正确实现,但我还是相当新的Java,我找不到处理并行线程的解释,我能理解。我是否需要从父进程调用Cycle和Metro线程?
编辑:更新的代码:现在的问题是,而不是实际并行运行,Cycle对象等待执行timer.ticking方法,然后在Metro休眠时执行它应该执行的操作然后卡住等待永远不会来的通知。这意味着线程实际上并不是彼此并行执行。
答案 0 :(得分:1)
我猜是因为你在没有锁定对象this.wait()
的情况下调用this
。
尝试先锁定。
synchronized (this) {
this.wait();
}
答案 1 :(得分:1)
Kennedy's回答提供了您询问异常问题的解决方案,但更大的问题是您只使用一个线程wait()
/ notify()
。应该调用playback()
的线程是执行ticking()
的线程,因此它会暂停四分之一节拍。我喜欢循环,试着按时完成:
void cycle()
throws InterruptedException
{
int endPoint = LevelStructure.getChunkTotal();
for (int chunk = 0; chunk < endPoint; chunk++) {
LevelStructure.setActiveChunk(chunk);
for (int quartBeat = 0; quartBeat < 64; quartBeat++) {
long start = System.nanoTime();
Player.playback(LevelStructure.getQuartBeat(quartBeat));
long delay = 15_000_000_000L / BPM - (System.nanoTime() - start);
if (delay < 0)
throw new IllegalStateException("Allotted time exceeded");
if (delay > 0)
Thread.sleep(delay / 1_000_000, delay % 1_000_000);
}
}
}
如果您觉得需要多线程,这是一个更复杂的方法。从本质上讲,它依赖于CyclicBarrier
来协调工作者和计时器。您还可以使用ScheduledExecutorService
将消息安排到合成器。
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
class Test
{
private final CyclicBarrier sync = new CyclicBarrier(2);
/** Duration of quarter beat in milliseconds. */
private final int qb;
Test(int bpm)
{
qb = 15000 / bpm;
}
private void cycle()
throws InterruptedException, BrokenBarrierException
{
Timer timer = new Timer();
timer.start();
sync.await();
for (int chunk = 0; chunk < 4; ++chunk)
chunk();
timer.interrupt();
}
private void chunk()
throws InterruptedException, BrokenBarrierException
{
long t1 = System.nanoTime();
for (int count = 0; count < 64; ++count) {
playback();
long t2 = System.nanoTime();
sync.await(); /* Now wait the remaining time, if any. */
long t3 = System.nanoTime();
float t = TimeUnit.NANOSECONDS.toMillis(t2 - t1) / 1000F;
float c = TimeUnit.NANOSECONDS.toMillis(t3 - t1) / 1000F;
System.out.printf("Task: %5.3f, Cycle: %5.3f seconds%n", t, c);
t1 = t3;
}
}
void playback()
{
/* Simulate performing some work sleeping a random time which is,
* on average, an eighth of a beat, but can "jank" occasionally by taking
* too long to do its job. */
long delay = (long) (-qb / 2 * Math.log(1 - Math.random()));
// long delay = qb / 2; /* Simulate a predictable workload. */
try {
Thread.sleep(delay);
}
catch (InterruptedException abort) {
Thread.currentThread().interrupt();
}
}
private final class Timer
extends Thread
{
@Override
public void run()
{
try {
sync.await();
while (true) {
Thread.sleep(qb);
sync.await();
}
}
catch (InterruptedException abort) {
return;
}
catch (BrokenBarrierException ex) {
ex.printStackTrace();
}
}
};
public static void main(String... argv)
throws Exception
{
Test player = new Test(120);
long t0 = System.nanoTime();
player.cycle();
System.out.printf("Total: %5.3f seconds%n", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0) / 1000F);
}
}