我正在为一个音乐播放器做一个图形用户界面,我有两个按钮,我想在同一个线程上运行,但是在不同的动作监听器上,一个是播放音乐,一个是停止音乐。下面是我的代码:
ActionListener bl2 = new ActionListener() { // play button
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("listener1" + Thread.currentThread().getName());
System.out.println("beep"); //created a new thread here so that my GUI won't freeze up
Runnable runnable = () -> {
cl.play();
};
Thread thread = new Thread(runnable);
thread.start();
}
};
ActionListener bl3 = new ActionListener() { //supposedly to stop the music which the other thread is running
@Override
public void actionPerformed(ActionEvent e) {
cl.stop();
}
};我还有一个暂停按钮,可以暂停音乐。我的问题是,我不知道如何停止我的音乐,每当我点击停止按钮,在我的GUI中,它执行(我让方法打印出来,每当它被调用),但不会停止音乐,这就是为什么我认为,为了停止我的音乐,我需要调用我的方法在同一线程中的播放按钮,这是正确的吗?我该怎么做?谢谢。
发布于 2021-12-02 16:05:33
你不需要像在运行线程中那样调用相同的方法,你可以在“control”线程上的同步方法中使用一个共享的“volatile”布尔值。
让我们将这个布尔值命名为"isPlaying";然后在运行线程中频繁地检查这个布尔值。在控制器类中,如果你想让Runner线程停止播放,你可以将这个布尔值更改为false,然后你可以继续检查这个值,当它返回到true时,你可以再次开始播放(这需要在循环的方法之间进行一些调用,但这是可行的)。
如果你想保存它停止播放的位置,你可以在Runner线程中不断地将该位置保存在一个很长的字段中,我不认为控制线程需要访问它(除非你想在一个字段中显示它)。
简短的示例:
public class Example {
static volatile boolean isPlaying;
public static void main(String[] args) throws InterruptedException {
//runner
Runnable runnable = () -> {
try {
Example.play();
} catch (InterruptedException ex) {
System.out.println("fail");
}
};
Thread thread = new Thread(runnable);
thread.start();
//control
Runnable runnable2 = () -> {
Example.stopButton();
};
Thread thread2 = new Thread(runnable2);
thread2.start();
Thread.sleep(5000);
Example.stopButton();
}
public static void play() throws InterruptedException {
isPlaying = true;
int i = 0;
while (isPlaying) {
//code to play music
System.out.println("playing - " + i);
i++;
Thread.sleep(1000);
}
System.out.println("Out of loop, stopped playing");
}
public static void stopButton() {
synchronized (Example.class) {
isPlaying = false;
}
}
}https://stackoverflow.com/questions/70202279
复制相似问题