简体   繁体   English

如何在Java中停止正在运行的音乐线程?

[英]How do I stop a running music thread in Java?

I have a class that plays background music on infinite loop for a game. 我有一个课程,在游戏的无限循环中播放背景音乐。 I want it to stop when another class calls the stopPlaying() method on the BackgroundMusic object. 我希望它在另一个类调用BackgroundMusic对象上的stopPlaying()方法时停止。 According to Oracle docs, there is no way to stop a thread in Java. 根据Oracle文档,没有办法在Java中停止线程。

It said to use a variable that it checks and stops when the variable is a certain value. 它说使用它检查的变量,当变量是某个值时停止。 I tried making a boolean running that gets set to false when I call stopPlaying() and tried making the while loop have running as the condition instead of true, but that did not work without a delay. 当我调用stopPlaying()并尝试使while循环作为条件而不是true运行时,我尝试进行布尔运行设置为false,但是没有延迟就行不通。 (Message edited from before) (之前编辑的消息)

I would put my class in here, but this site keeps saying it's not formatted properly, and I've done this before (pasting from Eclipse). 我会把我的课程放在这里,但这个网站一直说它没有正确格式化,我之前已经完成了这个(从Eclipse粘贴)。 I put it on PasteBin: http://pastebin.com/edCH2DXE 我把它放在PasteBin上: http ://pastebin.com/edCH2DXE

It's kind of a big hammer, but you can interrupt the thread by calling musicThread.interrupt() . 这是一个很大的锤子,但你可以通过调用musicThread.interrupt()中断线程。 This will cause isInterrupted() to return true for the music thread. 这将导致isInterrupted()为音乐线程返回true If the thread was doing some blocking I/O at the time, this might cause InterruptedException to be thrown, so you need to catch that as well: 如果线程当时正在执行一些阻塞I / O,则可能导致抛出InterruptedException ,因此您还需要捕获它:

  try {
    while (!Thread.currentThread().isInterrupted()) {
       // play music
    }
  } catch (InterruptedException ex) {
    // any cleanup necessary
  }

Again, it's a big hammer, and it's better to use the boolean flag approach if you can. 同样,它是一个很大的锤子,如果可以的话,最好使用布尔标志方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM