Open In App

Java Multithreading Program with Example

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Multithreading is a concept in which our program can do multiple tasks in a single unit of time. Thread is the execution unit of any process. Every process must have one thread and that thread name is the main thread. In this article. We will create a Java program that will do writing on file until the user gives input on the terminal. Here, We need two threads. One thread does writing on file and another waits for user input on the terminal. 

Java Program and Explanation

Here, One thread is doing writing on file, and the other thread will wait for user input on the terminal. Main class is executed on the parent thread and also it creates a child thread that will do writing on file.

Tasks of Parent thread:

  • Creates child thread which writes on file.
  • Waits for user input on the terminal.

Tasks of Child thread:

  • Do writing on text file until the user gives input on the terminal.

Main.java

Java




import java.lang.*;
import java.util.Scanner;
 
public class Main {
    // turned to be true when user entered
    // something on terminal
    public static boolean stop = false;
 
    // Parent thread
    public static void main(String args[])
    {
        // object of class which do writing task.
        WriteOnFile newFile = new WriteOnFile(
            "Anjali loves GeeksforGeeks.", "File.txt");
        // execute it on different thread...child
        // thread...it will execute run method of
        // WriteOnFile class
        newFile.start();
 
        Scanner sc = new Scanner(System.in);
 
        System.out.print("Enter Something : ");
        // waits for user input
        sc.nextLine();
        // turned on after entering input by user and it
        // tells another thread to stop writing
        Main.stop = true;
 
        return;
    }
}


Explanation of the above code:

  • It creates an object of WriteOnFile Class which extends the Thread class.
  • After this, it invokes the start() method which executes WriteOnFile run() method on a different thread i.e. child thread.
  • After this, It waits for user input on the terminal. 

WriteOnFile.java

Java




import java.io.File;
import java.io.FileWriter;
import java.lang.*;
import java.util.Scanner;
 
class WriteOnFile extends Thread {
    private String mssg, fileName;
 
    // read text of file and returns it so that we can
    // append our string to this text
    private String readFile()
    {
        String currText = "";
        try {
            // object of File class
            File myFile = new File(this.fileName);
            Scanner myReader = new Scanner(myFile);
            while (myReader.hasNextLine()) {
                // reads lines of text file and concatenate
                // it to currText
                currText += myReader.nextLine();
                currText += "\n";
            }
        }
        catch (Exception err) {
        }
        return currText;
    }
 
    // helps to write on file
    private void write()
    {
        // writes until Main.stop is false. if it's value
        // becomes true then it will stop writing
        while (Main.stop == false) {
            try {
                // gives the current text present in our
                // file. It will help us to append the text
                // in our text file and not overwriting on
                // file
                String currText = readFile();
 
                // object of FileWriter class which helps to
                // write on file
                FileWriter myWriter
                    = new FileWriter(fileName);
 
                // writes on given file
                myWriter.write(currText + this.mssg);
 
                // closing the writing stream
                myWriter.close();
 
                // puts this thread on sleep state for 1.5
                // seconds...it will gives more good
                // experience of writing
                Thread.sleep(1500);
            }
            catch (Exception err) {
            }
        }
        return;
    }
 
    // constructor
    public WriteOnFile(String mssg, String fileName)
    {
        this.mssg = mssg;
        this.fileName = fileName;
    }
    // start method calls this method (start calling is at
    // Main.java)
    public void run()
    {
        // run method calls write method which writes on
        // file
        this.write();
    }
}


Explanation of the above code:

  • We inherit our class WriteOnFile to Thread class which helps us to make our program multithreaded.
  • It’s run() method is invoked internally whenever we invoke the start() method of Main.java.
  • The run() method will do writing on the file until the start variable value is true and its value is false until the user has not entered any input on the terminal.

Output:

The output of the above demonstration - As you can see main thread waits for input in the terminal and another thread is writing on File.txt

The output of the above demonstration – As you can see main thread waits for input in the terminal and another thread is writing on File.txt 

Note: Give the proper path to the text file on which you want to write. Here our file presents in the same folder so we only gave the file name.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads