Start a thread
Your thread will only start if you call the start
method explicitly. Here is the documentation Thread#start. The start
method will then internally invoke the run
method of your Thread
.
Your code could then look like this:
public static void writeToFileAsync(final String saveState, final String fileName) {
// Create the thread
Thread fileWriter = new Thread() {
@Override
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
// Do nothing
}
}
};
// Start the thread
fileWriter.start();
}
And you probably want to remove the start();
call inside your run
method.
Semicolon
You need the ;
after the Thread
creation because you are using an assignment:
Thread fileWriter = new Thread() { ... };
The concept you are using here is called anonymous class. Basically it is the same as if creating a new class like:
public class FileWriter extends Thread {
@Override
public void run() {
...
}
}
And then using it like:
Thread fileWriter = new FileWriter();
However an important difference is that your anonymous class has access to your local variables (the scope of that method). And that it is anonymous, so it's like a small single-time usage class.