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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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();  
    }
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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();  
    }
 
    
}
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

Karibasappa G C (KB)
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