我试图利用 Java弹片物体发出信号。 我从头开始,我等着STOP活动才开始,直到我继续read。 我注意到,如果我离开了我的申请中可能出现的电话线索,则电线不会起作用,或者只起作用。
然而,大多数时间都是如此,每次大约50次,无论是《裁武条约》还是“STOP”活动都没有发射,造成目前的read望永远等待。
现在的问题是,我是否对使我松散事件的私刑有过错?
private static volatile boolean isPlaying = false;
private static final Object waitObject = new Object();
public static void playClip(...)
...
Clip clip = (Clip) AudioSystem.getLine(...);
clip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
synchronized (waitObject) {
isPlaying = false;
waitObject.notifyAll();
}
}
}
});
// start playing clip
synchronized (waitObject) {
isPlaying = true;
}
clip.start();
// keep Thread running otherwise the audio output is stopped when caller thread exits
try {
while (isPlaying) {
synchronized (waitObject) {
waitObject.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Here is the new version using
CountDownLatch
:
private static volatile CountDownLatch playingFinished = new CountDownLatch(1);
public static void playClip(...)
...
Clip clip = (Clip) AudioSystem.getLine(...);
clip.open(audioInputStream);
// use line listener to take care of synchronous call
clip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
playingFinished.countDown();
}
}
});
clip.start();
try {
playingFinished.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
playingFinished = new CountDownLatch(1);
I didn t include the debugging statements, but they indicate that the thread hangs in playingFinished.await();
because the STOP event was not fired and playingFinished.countDown();
is never called.