守护程序线程过多,导致程序失败

时间:2019-03-15 07:55:26

标签: java multithreading

我正在编写一个模仿鼓演奏的程序。您坐在摄像机前,碰到预定位置会导致程序播放一些声音。鼓不止一个,所以我必须在多线程中做到这一点,以便一个人可以同时演奏两个鼓(就像现实生活中可能发生的那样)。我播放音乐的方法如下:

void playInstrumentSound(InstrumentModel instrument) {

    System.out.println("Playing: " + instrument.getInstrumentName());
    if (instrument.getMedia() != null) {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                instrument.setPlaying(true);
                MediaPlayer player = new MediaPlayer(instrument.getMedia());
                player.setVolume(instrument.getVolume());
                player.play();
                try {
                    Thread.sleep(sleepLength);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                instrument.setPlaying(false);
            }
        });
        t.start();

    }
}

一个参数是我的乐器模型,这里有一个构造函数:

public InstrumentModel(String instrumentName, float[] coordinates, String pathToSound, float diameter, float addToSpineX,
        float addToSpineY, float addToSpineZ) {
    this.instrumentName = instrumentName;
    this.coordinates = coordinates;
    this.pathToSound = pathToSound;
    this.diameter = diameter;
    this.addToSpineX = addToSpineX;
    this.addToSpineY = addToSpineY;
    this.addToSpineZ = addToSpineZ;

    this.leftHandHighestDistance = 0;
    this.rightHandHighestDistance = 0;
    this.volume = 0;

    this.leftHandMovingCloser = false;
    this.rightHandMovingCloser = false;

    if (this.pathToSound != null) {
        media = new Media(new File(this.pathToSound).toURI().toString());
        setMedia(media);
    }
}

在这种情况下,最重要的是声音的路径。我的声音全都放在src/main/resources中,当我创建对象时,我会传递类似src/main/resources/snareDrum.wav的声音。基于此路径,它将创建Media对象(from javafx.scene.media),以便在播放音乐的方法中可以使用它。它可以正常工作,但是问题是,经过一段时间后,当我敲鼓时仍能看到Playing: ...,但程序不再播放声音。它总是在线程Timer-62之后发生。您可以在此处查看它:

enter image description here

每次我敲鼓时,都会创建2个线程-一个来自JFXMedia,另一个显示“ Timer-xx”。就像我说的那样,在一个叫“ Timer-62”的声音之后,我再也听不到声音了。你知道为什么会发生吗?预先谢谢你。

0 个答案:

没有答案