+92 332 4229 857 99ProjectIdeas@Gmail.com

Reading Files Simultaneously (Java_Threading)



The following code demonstrates how we can read multiple files simultaneously using threading technique in java....

Code

import java.io.*;

 public class TReader implements Runnable {

       private String fileName;
       
       //Parameterized Constructor
        public TReader(String _fileName) {
      
              this.fileName = _fileName;
       }
      
       public void run() {
      
       try {
             
             String line = null;
             BufferedReader br = new BufferedReader(new FileReader(fileName));
             
             line = br.readLine();
                   
                  while ( line != null ) {
                    
                    System.out.println(line);
                    line  = br.readLine();
                 }
                    
         } catch (IOException e) {
      
              e.printStackTrace();

       }
             
  }
      
       public static void main(String[] args) {
             
              TReader tr1 = new TReader("abc.txt");
              TReader tr2 = new TReader("abc2.txt");
              TReader tr3 = new TReader("abc3.txt");
             
              Thread t1 = new Thread(tr1);
              Thread t2 = new Thread(tr2);
              Thread t3 = new Thread(tr3);
             
              t1.start();
              t2.start();
              t3.start();

       }
}

0 comments: