我有以下代码,当用户在输入线程中输入所需的整数时,我需要停止声音线程(比方说5)。任何帮助表示赞赏。
public class crytask {
public static void main(String args[]) {
Runnable sound = new sound();
final Thread soundthread = new Thread(sound);
Runnable input = new input();
final Thread inputthread = new Thread(input);
soundthread.start();
inputthread.start();
}}
class sound implements Runnable{
public void run(){
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("/Users/babe/Desktop/C1.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
Thread.sleep(clip.getMicrosecondLength() / 1000);
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
}
class input implements Runnable{
public void run(){
System.out.println("Enter");
Scanner reader = new Scanner(System.in);
}
}
答案 0 :(得分:0)
根本不需要输入线程:主线程可以用于此。停止Thread.sleep
使用Thread.interrupt()
:
public class crytask {
public static void main(String args[]) {
Runnable sound = new sound();
final Thread soundthread = new Thread(sound);
soundthread.start();
System.out.println("Enter");
Scanner reader = new Scanner(System.in);
reader.nextLine();
soundthread.interrupt();
}
}
class sound implements Runnable {
@Override
public void run() {
try {
AudioInputStream audioInputStream = AudioSystem
.getAudioInputStream(new File("/Users/babe/Desktop/C1.wav")
.getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
Thread.sleep(clip.getMicrosecondLength() / 1000);
} catch(InterruptedException ex) {
System.out.println("Cancelled!");
} catch (Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
}