Reputation: 279
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.
Upvotes: 1
Views: 351
Reputation: 432
I think you should pring the log PlayEngine's run method very first. Moreover It appears you have written the playback code in start method(which runs in main thread) instead of run method. To get the playback done in background put the code in start in run method by overriding that.
Upvotes: 0
Reputation: 340763
overwrote its
Start()
I suspect you overriden Thread.start()
which will never work. Either override Thread.run()
or supply your own instance of Runnable
to thread.
Upvotes: 2
Reputation: 328639
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);
}
}
Then start the tread with:
PlayEngine plengine = new PlayEngine(file);
Thread t = new Thread(plengine);
t.start();
System.out.println("Next task:");
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.
Upvotes: 6