将线程发送到后台 [英] Send thread to background

查看:60
本文介绍了将线程发送到后台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个音乐播放器.我编写了一个从 Thread 扩展的类,并覆盖了它的 Start()-Method 来播放随机歌曲.

I am trying to implement a music player. I wrote a class which extends from Thread and overwrote its Start()-Method to play a random song.

播放歌曲有效,但我想将该线程发送到后台,这不起作用:

Playing a song works, but I want to send that thread to the background, which doesn't work:

File file = new File("song.mp3");
PlayEngine plengine = new PlayEngine(); //This class extends from Thread

plengine.Play(file); //This just sets the file to play in a variable
plengine.Start(); //And this finally plays the file itself

System.out.println("Next task:"); // I don't get to this point. Only when the song has finished.

正如您在上面的代码中看到的,我想在启动线程后立即转到打印行.

As you can see in the code above, I'd like to go to the printed line right after launching the thread.

推荐答案

不建议扩展 Thread - 让你的 PlayEngine 实现 Runnable> 代替,并覆盖 run 方法:

It is not recommended to extend Thread - Have your PlayEngine implement Runnable instead, and override the run method:

class PlayEngine implements Runnable {
    private final File file;

    PlayEngine(File file) {
        this.file = file;
    }

    @Override
    public void run() {
        //do your stuff here
        play(file);
    }
}

然后开始踏步:

PlayEngine plengine = new PlayEngine(file);
Thread t = new Thread(plengine);
t.start();
System.out.println("Next task:");

Next task 应该立即打印.在您的示例中,您似乎在主线程中调用了长时间运行的方法 play,这就解释了为什么它不会立即返回.

and Next task should print immediately. In your example, you seem to be calling the long running method play in the main thread, which explains why it does not return immediately.

这篇关于将线程发送到后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆