Java Program on Multithreading Concept

Aim:

To write a java program on multithreading concept.

Algorithm:

  1. Start the program
  2. Create the main thread called ThreadDemo and starts its execution
  3. 3.Invoke the child thread class called newThread
  4. newThread() invokes the superclass constructor and starts the child thread execution.
  5. Main thread and child thread runs parallelly.
  6. Display the result.

Program:

import java.util.Scanner;
class ThreadDemo extends Thread 
{
ThreadDemo()
{
System.out.println("MAIN THREAD IS RUNNING");
}
public void run() {
try 
{
Scanner put=new Scanner(System.in);
System.out.println("ENTER THE NAME OF CHILD THREAD");
String tname=put.next();
newthread r1=new newthread(tname);
r1.start();
System.out.println("MAIN THREAD INVOKE NEW THREAD");
int result=1;
for(int i=1;i<=5;i++)
result=result+i;
System.out.println("MAIN THREAD CALCULATE SUM OF NUMBER="+result);
} 
catch (Exception e) 
{
System.out.println("FAILED TO INVOKE NEW THREAD");
}
}
}
class newthread extends Thread 
{
newthread(String str )
{
super(str);
}
public void run() {
try {
int result=1;
for(int i=1;i<=5;i++)
result=result*i;
System.out.println(getName()+" CALCULATE PRODUCT OF NUMBER="+result); 
} 
catch (Exception e) 
{
System.out.println("exception is occured");
}
}
}
public class Main{
public static void main(String[]args)
{
ThreadDemo A=new ThreadDemo();
A.start();
}
}

Execution:

INPUT : 
MAIN THREAD IS RUNNING
ENTER THE NAME OF CHILD THREAD  : Child1

OUTPUT : 
MAIN THREAD INVOKE NEW THREAD
MAIN THREAD CALCULATE SUM OF NUMBERS = 16
Child CALCULATE PRODUCT OF NUMBER = 120

Leave a Comment