GBleaney
GBleaney

Reputation: 2196

How to pass information into new Thread(..);

I playing a sound file, and I create a new thread every time the playSoundFile() method is called. I just need to know how to pass the information from the method call into run() within the thread, so It can be used within.

        public void playSoundFile(File file) {//http://java.ittoolbox.com/groups/technical-functional/java-l/sound-in-an-application-90681
            new Thread(
                    new Runnable() {

                        public void run() {

                            try {
    //get an AudioInputStream
    //this input stream can't use the file passed to playSoundFile()
                                AudioInputStream ais = AudioSystem.getAudioInputStream(file);
                                ...
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

        }

Upvotes: 1

Views: 306

Answers (3)

templatetypedef
templatetypedef

Reputation: 372684

Anonymous inner classes (like the Runnable you're creating here) can reference final local variables from their enclosing scope. If you want access to the file parameter, change the function to make it final:

public void playSoundFile(final File file) {
    /* ... */
}

Now, your new Runnable can reference this variable without problems.

Upvotes: 3

EboMike
EboMike

Reputation: 77722

public void playSoundFile(final File file) 

Problem solved. Inner classes can only access final variables of the parent function.

If you have a lot of information, subclass Thread or Runnable and add member variables.

EDIT: What's the point of the new Runnable in your example? Thread already implements Runnable.

Upvotes: 3

Andrzej Doyle
Andrzej Doyle

Reputation: 103777

Simply declare the variable to be final, then you can use it in your anonymous inner class:

public void playSoundFile(final File file) {
   ...

Upvotes: 4

Related Questions