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
开发者_StackOverflow 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();
}
Simply declare the variable to be final
, then you can use it in your anonymous inner class:
public void playSoundFile(final File file) {
...
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
.
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.
精彩评论