by colfre » Thu Jul 26, 2012 2:49 am
I'm not a real Java expert, but probably know enough to be dangerous ;-)
I think a better solution is to create a class that extends Thread. Pass the file name to the constructor for this class, and stuff it away in a variable. The call start on the object.
class FileAnalyzer extends Thread {
string fileName;
FileAnalyzer (string f) {
this.fileName= f;
}
public void run() { // Do stuff with file }
}
Caller does:
FileAnalyzer f = new FileAnalyzer(filename);
f.start();
What that doesn't cover, and what I don't quite get, is " all of the threads use runner(for synchronization)". Why do they need to synchronize? Nothing in your problem description suggests a need for the threads to synchronize. Not that there isn't one, I just don't see it from what you asked. It seems like reading a file, and writing output based on stuff in that file is a rather independent task with no need for synchronization?
How many files do you need to process at once? At some point, your solution of 1 thread per file will run into performance issues. If you only have 10 files, you are good. If you have a million files, you will probably bury even the best hardware. For some number in between (which depends a lot on the capabilities of your server and the amount of processing you need to do) your solution will start to run too slowly. If you have a really large set of files (or might have, 2 years from now), you might want to think about a thread pooling scheme. You put the 1 million files in a queue to be processed, and you have some number (100? 1000? 10000? only stress testing will tell you the magic number) of threads that take the next item out of the queue and process it. That is, of course, a bit harder to implement. But it isn't all that bad. Java has a rich API for these sorts of problems.