代码
import javax.sound.sampled.*;
import java.io.*;
public class Tester {
static Thread th;
public static void main(String[] args) {
startNewThread();
while( th.isAlive() == true) {
System.out.println("sound thread is working");
}
}
public static void startNewThread() {
Runnable r = new Runnable() {
public void run() {
startPlaying();
}
};
th =new Thread(r);
th.start();
}
public static void startPlaying() {
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("d:/UnderTest/wavtester.wav"));
Clip clip = AudioSystem.getClip();
clip.open(ais);
clip.loop(-1); // keep playing the sound
} catch(Exception exc) {
System.out.println(exc);
}
}
}
这段代码输出“sound thread working”,但没有播放任何声音。在这段代码中,我启动了一个单独的线程来播放声音,程序不应该在声音线程完成任务之前终止。但程序在打印一系列“sound thread working”后终止了。
造成程序终止和声音未播放的原因是什么?
clip
生成的守护线程完成后才会终止。但我不知道它在播放3-4秒后为什么会结束。 - Suhail GuptaJOptionPane
出现一会儿就自动消失了。我之前发布过这个问题,但没有得到有意义的答案。http://stackoverflow.com/questions/6594921/how-does-boolean-here-become-false-on-its-own - Suhail GuptaJOptionPane
出现一会儿就自动消失了。”我能想到唯一的解释是“你的 Java 安装已经损坏了”。 - Andrew Thompson