Can anyone give me the working example of reading two files simultaneously through threads? and also what would be the best way to read them at one time.
public static void main(String args[]) {
new Runnable(new File("D:/test1.log"),"thread1");
new Runnable(new File("D:/test2.log"),"thread2");
}
private static class Runnable implements Runnable {
private File logFilePath;
Thread runner;
// you should inject the file path of the log file to watch
public Runnable(File logFilePath,String threadName) {
this.logFilePath = logFilePath;
runner = new Thread(this, threadName);
runner.start();
}
_____READ LOGIC HERE____
}
Program that generates logs.I am not using any close or flush .
public final class Slf4jSample {
static Logger logger = LoggerFactory.getLogger(Slf4jSample.class);
static int i=0;
public static void main(final String[] args) {
int delay = 0; // delay for 5 sec.
int period = 10000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// Task here ...
logger.error("error"+i);
logger.warn("warn"+i);
logger.debug("debug"+i);
try{int i=0/0;
}catch(Exception e){
logger.error("Ecxeption"+i, e);
}
i++;
}
}, delay, period);
}
}
I’m not quite sure what your aim is from the short description, but I just want to warn you that reading files in parallel from a single hard disk is generally not a good idea, because the mechanical disk head needs to seek the next reading location and so reading with multiple threads will cause it to keep bouncing around and slow things down instead of speeding them up.
In case you want to read portions of files and process them in paralle, I recommend you to look at a single producer (to read the files sequentially) multiple consumer (to process the files) solution.
Edit: If you insist on using multiple readers, you should probably change your code like this: