Saturday, 2 April 2016

Read two different files using multiple threads simultaneously in Java

In this program, we will use different threads to read two different files simultaneously.
Here we have two files number.txt and alpha.txt.



Here we created a class ReadFileByThread which extends Thread class. So ReadFileByThread  class will override the method Run() of thread class. By using ReadFileByThread (String filename) constructor, we will pass filenames at the time of object creation in main() method.

In run() method, we will read file by using wrapper of FileReader and BufferedReader class and print the data of file line by line onto the screen. We used Thread's static Sleep() method to check the behaviour of threads.

Source code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileByThread extends Thread {
      File alpha;
     
      public ReadFileByThread(String filename) {
             alpha=new File(filename);
           
      }

      public  void run() {
           
            try {
                  FileReader fr=new FileReader(alpha);
                  BufferedReader br=new BufferedReader(fr);
                  String line;
                  try {
                        while ((line=br.readLine())!=null) {
                              System.out.println(Thread.currentThread().getName()+": "+line);
                             
                        }
                  } catch (IOException e) {
                        e.printStackTrace();
                  }
            } catch (FileNotFoundException e) {
                  e.printStackTrace();
            }
           
      }
     
      public static void main(String[] args) {
           
            ReadFileByThread one=new ReadFileByThread("alpha.txt");
            ReadFileByThread two=new ReadFileByThread("number.txt");
            System.out.println(Thread.currentThread().getName()+" is our Thread-1 thread");
            Thread t1=new Thread(one);
            Thread t2=new Thread(two);
            t1.start();
            t2.start();
            try {
                  Thread.sleep(5000);
            } catch (InterruptedException e) {
                  e.printStackTrace();

            }}}

Both the thread t1 and t2 will execute simultaneously. Thread t1 will work on 'one' object where we passed alpha.txt and t2 will work on 'two' object with file number.txt.  Check the below screenshot for output of above program.




No comments:

Post a Comment