2017-09-27 145 views
0

我創建了一個線程,從一個實現的Runnable類(Soundtrack)播放歌曲,我想通過按下我的按鈕(jMenuItem1ActionPerformed)來停止它。我GOOGLE了&嘗試了很多方法來阻止但失敗我認爲在我的情況下還有另一種方法來做到這一點。下面的下面的代碼:如何通過按下Java Swing按鈕來停止線程?

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

你可以調用player.stop()或類似的東西? – jwils

+0

沒有我不能,但有player.close(),我不能稱它像播放器播放器=新播放器(); player.close();我不得不把所有的嘗試和catch命令,即使仍然無法正常工作,我認爲Player類不是來自Java最初我從http://www.javazoom.net/index.shtml添加了一個新的庫JLayer 1.0.1爲了播放mp3文件,這些是我可以在播放器中設置的命令。: close(); equals(Object o);的getClass();爲getPosition();的hashCode();做完了();通知(); notifyAll的();玩();玩(int i);的toString();等待();等待(long l);等待(long l,int i)。 – Rafa

回答

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

正確。但是,您可能會從學習[executors](https://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html)和'Future'獲益。 –