如何在停止程序之前等待命令完成执行?

How do I wait for a command to finish executing before stopping the program?

这是我的代码:

import java.io.File;
import jaco.mp3.player.MP3Player;

class SimpleAudioPlayer {

    public static void main(String[] args) {

        File audio_file = new File("Clarx - H.A.Y.mp3");
        MP3Player music_player = new MP3Player();
        music_player.addToPlayList(audio_file);
        music_player.play();
        // wait for music_player.play() to finish executing
    }
}

我想创建一个 mp3 播放器并发现 this Project,代码片段所做的是创建一个新的 MP3Player 对象,创建一个新的文件,并将其添加到播放列表中。之后,它才开始播放歌曲。但问题是它在程序停止执行之前只播放了大约一两秒的文件。如何等到 play() 函数停止执行?

答案: 感谢 giraycoskun 的帮助!

import java.io.File;
import jaco.mp3.player.MP3Player;
import java.util.concurrent.*;

class SimpleAudioPlayer {

    public static void main(String[] args) {

        File audio_file = new File("Clarx - H.A.Y.mp3");
        MP3Player music_player = new MP3Player();
        music_player.addToPlayList(audio_file);
        ExecutorService threadpool = Executors.newCachedThreadPool();
        Future<Long> futureTask;
        futureTask = (Future<Long>) threadpool.submit(music_player::play);
        // Simple variable to check hpw often the folowing loop gets executed
        int n = 0;
        while (!futureTask.isDone()) {
            System.out.println("Executing" + n);
            n++;
        }
    }
}

我不得不对他提交的答案做一些小改动,但效果很好,非常感谢!

我还没有在我的电脑上尝试过这些代码,但是这些可以帮助:

https://docs.oracle.com/javase/8/docs/api/?java/util/concurrent/package-summary.html

https://www.baeldung.com/java-asynchronous-programming

import java.io.File;
import jaco.mp3.player.MP3Player;
import java.util.concurrent;

class SimpleAudioPlayer {

    public static void main(String[] args) {

        File audio_file = new File("Clarx - H.A.Y.mp3");
        MP3Player music_player = new MP3Player();
        music_player.addToPlayList(audio_file);
        ExecutorService threadpool = Executors.newCachedThreadPool();
        Future<Long> futureTask = threadpool.submit(() -> music_player.play());
        while (!futureTask.isDone()) {
            // wait for music_player.play() to finish executing
            System.out.println("FutureTask is not finished yet..."); 
        } 
        
        
    }
}