Java Multithreading – One Thread to Take Input, Another to Print on Console
Last Updated :
07 Feb, 2023
Multithreading is a concept in which our program can do two or more tasks at the same time. Thread is the execution unit of any process. Every process has at least one thread which is called main thread. In this article, we will create a Java program that will do printing on the console until the user gives input. Here, we need two threads. One thread do printing and another waits for user input.
Java Program and Explanation
Here, one thread is printing on the console and while the other thread will wait for user input. Main class is executed on the parent thread and also it creates a child thread that does printing on the console.
Tasks of Parent thread:
- Create a new thread. (child thread)
- Waits for user input.
Tasks of child thread:
Java
import java.lang.*;
public class GeeksForGeeks extends Thread {
private String mssg;
GeeksForGeeks(String mssg)
{
this .mssg = mssg;
}
public void run()
{
while (Main.start == true ) {
System.out.println( this .mssg);
try {
Thread.sleep( 1500 );
}
catch (Exception err) {
}
}
}
}
|
Explanation of the above code:
- We extend our class to Thread class to make our program multithreaded.
- its run() method is invoked internally whenever we invoke the start() method.
- run() methods do printing until the start variable value is true.
Java
import java.lang.*;
import java.util.Scanner;
public class Main {
public static boolean start = true ;
public static void main(String args[])
{
GeeksForGeeks newThread = new GeeksForGeeks( "I Love GFG!" );
newThread.start();
Scanner sc = new Scanner(System.in);
sc.nextLine();
Main.start = false ;
}
}
|
Explanation of the above code:
- It creates an object of GeeksForGeeks Class which extends the Thread class.
- After this, it invokes the start() method which executes all the code of the GeeksForGeeks run() method on a different thread.
- After that, It waits for user input.
Output: printing and waiting for user input at the same time
printing and waiting for user input at the same time
Both classes in the same Java file:
Java
import java.io.*;
import java.lang.*;
import java.util.Scanner;
class GeeksForGeeks extends Thread {
private String mssg;
GeeksForGeeks(String mssg)
{
this .mssg = mssg;
}
public void run()
{
while (Main.start == true ) {
System.out.println( this .mssg);
try {
Thread.sleep( 1000 );
}
catch (Exception err) {
}
}
}
}
public class Main {
public static boolean start = true ;
public static void main(String[] args)
{
GeeksForGeeks newThread = new GeeksForGeeks( "Manish Loves GFG!" );
newThread.start();
Scanner sc = new Scanner(System.in);
sc.nextLine();
Main.start = false ;
}
}
|
Output: printing and waiting for user input at the same time
printing and waiting for user input at the same time
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...