0

Either I don't actually understand multithreading, or something weird is happening.

I have the following piece of code:

public void playMusic(){
    new Thread(new Runnable(){
        public void run(){
            tune.play();
        }
    }).run();
    System.out.println("*******");
}

This method plays a piece of music. It starts a new thread and does the music-playing in there, to not pause the execution of the current thread.

As such I would expect System.out.println("*********"); to be executed almost immediately when the method is called, since the lengthy operation tune.play() is invoked on a different thread.

However in practice ********* is printed to the screen only when the music ends.

How do you explain this? And how can I separate the music-playing from the current thread?

If it makes a difference, the 'current thread' is the Swing EDT.

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131

2 Answers2

3

That's not how you start a new thread.

It should be :

public void playMusic(){
    new Thread(new Runnable(){
        public void run(){
            tune.play();
        }
    }).start();
    System.out.println("*******");
}

Calling the run method of the Thread you created will execute it on the current thread.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

You didn't start the thread, you merely called run on it, so it's executed in your current thread. Call start to start the thread instead. Change

}).run();

to

}).start();
rgettman
  • 176,041
  • 30
  • 275
  • 357