Multithreading in java

It says multiple tasks can be done at a time but actually its not exactly like that.
It will keep the cpu idle time less. Because cpu will have a responsibility to execute many threads if we
Use multithreading.
If its single threaded application then it might keep the cpu idle for some time and hence lowers the performance.

Lets see the same through example.

Requirement
Read multiple files from a location and write the content of each file to the same destination file by appending each time.

i have kept total 3000 files in the source location to read and i will create one thread to read and write one file content in multithreading scenario whereas in single thread scenario for loop iterates 3000 times to read and write 3000 files.

Lets use single threaded program

  1. package com.kb;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.File;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileReader;
  8. import java.io.FileWriter;
  9. import java.io.IOException;
  10.  
  11. public class SingleThreadWriteToFile {
  12.  
  13.     public static void main(String[] args) {
  14.         long startTime = System.nanoTime();
  15.        
  16.        
  17.         File dir = new File("E:\\java\\sample files");
  18.         File destination = new File("E:\\java\\sample files\\Destination.txt");
  19.         File[] files = dir.listFiles();
  20.         String content;
  21.         for (File file : files) {
  22.         content = readFromFile(file.getAbsolutePath());
  23.         writeToFile(destination,content);
  24.         }
  25.         long stopTime = System.nanoTime();
  26.        
  27. System.out.println("Total execution time is "+(stopTime - startTime));     
  28.     }
  29.    
  30.     private static void writeToFile(File file,String content) {
  31.         try {
  32.             BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
  33.             writer.write(content);
  34.             writer.flush();
  35.         } catch (IOException e) {
  36.             // TODO Auto-generated catch block
  37.             e.printStackTrace();
  38.         }
  39.        
  40.        
  41.     }
  42.  
  43.     static String readFromFile(String filename){
  44.         StringBuffer content = new StringBuffer();
  45.         try {
  46.             String text;
  47.             BufferedReader reader = new BufferedReader(new FileReader(filename));
  48.                 while((text = reader.readLine())!=null){
  49.                     content.append(text);
  50.                     content.append("\n");
  51.                    
  52.                 }
  53.              
  54.         } catch (FileNotFoundException e) {
  55.             // TODO Auto-generated catch block
  56.             e.printStackTrace();
  57.         }
  58.         catch (IOException e) {
  59.             // TODO Auto-generated catch block
  60.             e.printStackTrace();
  61.         }
  62.     return content.toString(); 
  63.     }
  64.  
  65. }
package com.kb;

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

public class SingleThreadWriteToFile {

	public static void main(String[] args) {
		long startTime = System.nanoTime();
		
		
		File dir = new File("E:\\java\\sample files");
		File destination = new File("E:\\java\\sample files\\Destination.txt");
		File[] files = dir.listFiles();
		String content;
		for (File file : files) {
		content = readFromFile(file.getAbsolutePath());
		writeToFile(destination,content);
		}
		long stopTime = System.nanoTime();
		
System.out.println("Total execution time is "+(stopTime - startTime));		
	}
	
	private static void writeToFile(File file,String content) {
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
			writer.write(content);
			writer.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	static String readFromFile(String filename){
		StringBuffer content = new StringBuffer();
		try {
			String text;
			BufferedReader reader = new BufferedReader(new FileReader(filename));
				while((text = reader.readLine())!=null){
					content.append(text);
					content.append("\n");
					
				}
			 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	return content.toString();	
	}

}

Output is

Now lets use multithreading to the above program.

Here how it goes

  1. package com.kb;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.File;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileReader;
  8. import java.io.FileWriter;
  9. import java.io.IOException;
  10.  
  11. public class MultithreadingWriteToFile {
  12.    
  13.     public static void main(String[] args) {
  14.         Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  15.         long startTime = System.nanoTime();
  16.         File dir = new File("E:\\java\\sample files");
  17.         File destination = new File("E:\\java\\sample files\\DestinationMultiThread.txt");
  18.         File[] files = dir.listFiles();
  19.         for (File file : files) {
  20.             Writer w1 = new Writer(file, destination);
  21.             Thread t = new Thread(w1);
  22.             t.setPriority(Thread.MAX_PRIORITY);
  23.             t.start();
  24.            
  25.         }
  26.         long stopTime = System.nanoTime();
  27.        
  28.    
  29. System.out.println("Total execution time is "+(stopTime - startTime));
  30.        
  31.     }
  32.  
  33. }
  34.  
  35. class Writer implements Runnable{
  36. File source;
  37. File destination;
  38.     public Writer(File source,File destination) {
  39. this.source = source;
  40. this.destination = destination;
  41.     }
  42.     @Override
  43.     public void run() {
  44.         String content;
  45.         content =   readFromFile(source.getAbsolutePath());
  46.         writeToFile(destination,content);      
  47.     }
  48.    
  49.     private static void writeToFile(File file,String content) {
  50.         try {
  51.             BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
  52.             writer.write(content);
  53.             writer.write("file content written");
  54.             writer.flush();
  55.         } catch (IOException e) {
  56.             // TODO Auto-generated catch block
  57.             e.printStackTrace();
  58.         }
  59.        
  60.        
  61.     }
  62.  
  63.     static String readFromFile(String filename){
  64.         StringBuffer content = new StringBuffer();
  65.         try {
  66.             String text;
  67.             BufferedReader reader = new BufferedReader(new FileReader(filename));
  68.                 while((text = reader.readLine())!=null){
  69.                     content.append(text);
  70.                     content.append("\n");
  71.                    
  72.                 }
  73.              
  74.         } catch (FileNotFoundException e) {
  75.             // TODO Auto-generated catch block
  76.             e.printStackTrace();
  77.         }
  78.         catch (IOException e) {
  79.             // TODO Auto-generated catch block
  80.             e.printStackTrace();
  81.         }
  82.     return content.toString(); 
  83.     }
  84.  
  85.    
  86. }
package com.kb;

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

public class MultithreadingWriteToFile {
	
	public static void main(String[] args) {
		Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
		long startTime = System.nanoTime();
		File dir = new File("E:\\java\\sample files");
		File destination = new File("E:\\java\\sample files\\DestinationMultiThread.txt");
		File[] files = dir.listFiles();
		for (File file : files) {
			Writer w1 = new Writer(file, destination);
			Thread t = new Thread(w1);
			t.setPriority(Thread.MAX_PRIORITY);
			t.start();
			
		}
		long stopTime = System.nanoTime();
		
	
System.out.println("Total execution time is "+(stopTime - startTime));
		
	}

}

class Writer implements Runnable{
File source;
File destination;
	public Writer(File source,File destination) {
this.source = source;
this.destination = destination;
	}
	@Override
	public void run() {
		String content;
		content = 	readFromFile(source.getAbsolutePath());
		writeToFile(destination,content);		
	}
	
	private static void writeToFile(File file,String content) {
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
			writer.write(content);
			writer.write("file content written");
			writer.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	static String readFromFile(String filename){
		StringBuffer content = new StringBuffer();
		try {
			String text;
			BufferedReader reader = new BufferedReader(new FileReader(filename));
				while((text = reader.readLine())!=null){
					content.append(text);
					content.append("\n");
					
				}
			 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	return content.toString();	
	}

	
}

Output is

See the time difference between each output is
396687651 nano seconds.

This is how multithreading helps us to achieve the performance.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on