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
  • 13,385
  • 22
  • 55
  • 111

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
  • 374,785
  • 51
  • 663
  • 734
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
  • 172,063
  • 28
  • 262
  • 343