【问题标题】:How to stop a Thread by pressing a Java Swing button?如何通过按下 Java Swing 按钮来停止线程?
【发布时间】:2017-09-27 18:37:11
【问题描述】:

我创建了一个线程,它播放来自已实现的 Runnable 类(音轨)的歌曲,我想通过按下我的按钮来停止它(jMenuItem1ActionPerformed)。我用谷歌搜索并尝试了很多方法来阻止但失败了我认为在我的情况下还有另一种方法可以做到这一点。以下代码如下:

public static class Soundtrack implements Runnable {
    @Override
    public void run() {
        try{
        File file = new File("SF.mp3");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);

        try{
            Player player = new Player(bis);
            player.play();
        }catch(JavaLayerException ex){}
    }catch(IOException e){}
    }
    }
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
}    
public static void main(String args[]) {
    Thread background = new Thread(new Soundtrack());
    background.start();
}  

【问题讨论】:

  • 你可以调用 player.stop() 或类似的方法吗?
  • 不,我不能,但是有 player.close(),我不能像 Player player = new Player();播放器.close();我不得不输入所有的 try 和 catch 命令,即使它仍然不起作用,我认为 Player 类最初不是来自 Java 我从javazoom.net/index.shtml 添加了一个新库 JLayer 1.0.1 为了播放 mp3 文件,这些是我可以在播放器中设置的命令:close();等于(对象 o);获取类();获取位置();哈希码();完成了();通知();通知所有();玩();播放(int i); toString();等待();等待(长 l );等待(长 l,int i)。

标签: java thread-safety background-music


【解决方案1】:

我要感谢我姐姐的解决方案:

public static class Soundtrack implements Runnable {
    @Override
    public void run() {
        try{
        File file = new File("SF.mp3");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);

        try{
            Player player = new Player(bis);
            player.play();
        }catch(JavaLayerException ex){}
    }catch(IOException e){}
    }
    }
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
        background.stop();     
}                                          
private static Thread background;
public static void main(String args[]) {
    background = new Thread(new Soundtrack());
    background.start();
}

【讨论】:

  • 正确。但是您可能会从了解executorsFuture 中受益。
  • 注意:Thread.stop() 已弃用,建议不要使用Thread.stop()。事实上,我尝试了Thread.stop() 试图停止 Swing 线程,但它不起作用。
猜你喜欢
  • 2023-04-03
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多