Aim
To write a program for demonstrating multithreading using Java.
Theory
A thread is a separate flow of execution in a program. All Java programs by default contain a single thread called the “Main thread”. A thread contains a set of statements like a method in Java. The difference between thread and a method is, unlike methods, threads can run simultaneously or in parallel with other threads.
Threads in Java are supported through Thread class and Runnable interface. A single thread is represented in a Java program as Thread class instance (object). To create a new thread in a Java program, we can either:
- Extend the Thread class or
- Implement the Runnable interface
Pseudo code / Steps
- Create a class MyThread and either implement Runnable interface or extend Thread
- Override the run
- Create three threads (objects).
- Every thread must display thread name followed by the text given in the next instruction.
- The first thread should display the text “Welcome”, second thread should display “To”, and third thread should display “Java”.
- Make each thread pause for 1 second (1000 milliseconds) after it prints the text.
Program
class MyThread extends Thread
{
String message;
MyThread(String m)
{
message = m;
}
public void run()
{
try
{
for(int i=0; i<3; i++)
{
System.out.println(this.getName() + "->" +
message);
this.sleep(1000);
}
}
catch(InterruptedException e)
{}
}
}
class ThreadDemo
{
public static void main(String args[])
{
new MyThread("Welcome").start();
new MyThread("To").start();
new MyThread("Java").start();
}
}
Input and Output:
Run1:
Thread-1->To
Thread-2->Java
Thread-0->Welcome
Thread-0->Welcome
Thread-1->To
Thread-2->Java
Thread-0->Welcome
Thread-1->To
Thread-2->Java
Run2:
Thread-0->Welcome
Thread-2->Java
Thread-1->To
Thread-2->Java
Thread-1->To
Thread-0->Welcome
Thread-0->Welcome
Thread-1->To
Thread-2->Java
Result
The concepts related to multithreading were understood and implemented successfully.

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply