如何通过按Java Swing按钮来停止线程?

时间:2017-09-27 18:37:12

标签: java thread-safety background-music

我创建了一个Thread,它从一个实现的Runnable类(Soundtrack)播放一首歌,我想按下我的按钮(jMenuItem1ActionPerformed)来阻止它。我google了它&尝试了很多方法来阻止但失败我认为在我的情况下还有另一种方法可以做到这一点。以下代码:

widget1 = widget.paper_trail.version(4)
widget2 = widget.paper_trail.version(10)
# there are a couple of way to get the diff 
# using active record diff ( I prefer this to Jeremy Weiskotten's PaperTrail)
changes = widget1.diff(widget2)
# I know I can do 
versions = widget.versions[4]  
# that only returns versions model instead of widget 

1 个答案:

答案 0 :(得分:0)

我想感谢我妹妹的解决方案:

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();
}