I'm doing some experiments about multithreading.
When the program runs to the output part, (using java.io.FileWriter)
sometimes it can go through quickly,
but sometimes it just stuck on there.
Is the FileWriter's problem?
Here is the simplified code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test extends Thread {
private int _id;
public Test(int id) {
_id = id;
}
@Override
public void run() {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
try (FileWriter fw = new FileWriter(new File(_id + ".txt"))) {
fw.write("hello!");
} catch (IOException e) {
System.err.println("Something wrong.");
}
}
System.out.println(_id + ": " + (System.currentTimeMillis() - start));
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Test(i).start();
}
}
}
And here is my result:
7: 3820 9: 3878 2: 3965 8: 3956 0: 4058 6: 4097 5: 4111 3: 4259 1: 4354 4: 4369
9: 4703 7: 4748 5: 4891 2: 4994 4: 5065 3: 5672 1: 5804 0: 5805 8: 5925 6: 6042
1: 4495 9: 5265 6: 5551 2: 5651 5: 5676 8: 5697 3: 5917 0: 6001 7: 6002 4: 6314
I runs it three times, why are the elapsed times different?
Is it the FileWriter's problem or the file system's?