In this article we will learn to implement a Java program that creates three threads. A java program is provided below to create three threads.
First thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds.
Program is as follows:
class ChildThread implements Runnable
{
Thread t;
ChildThread(String name)
{
t = new Thread(this, name);
t.start();
}
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
if(t.getName().equals("First Thread"))
{
Thread.sleep(1000);
System.out.println(t.getName()+": Good Morning");
}
else if(t.getName().equals("Second Thread"))
{
Thread.sleep(2000);
System.out.println(t.getName()+": Hello");
}
else
{
Thread.sleep(3000);
System.out.println(t.getName()+": Welcome");
}
}
catch(InterruptedException e)
{
System.out.println(t.getName()+" is interrupted");
}
}
}
}
class ThreeThreads
{
public static void main(String args[])
{
ChildThread one = new ChildThread("First Thread");
ChildThread two = new ChildThread("Second Thread");
ChildThread three = new ChildThread("Third Thread");
}
}
Output for the above program is as follows:
First Thread: Good Morning
Second Thread: Hello
First Thread: Good Morning
Third Thread: Welcome
First Thread: Good Morning
Second Thread: Hello
First Thread: Good Morning
First Thread: Good Morning
Third Thread: Welcome
Second Thread: Hello
Second Thread: Hello
Third Thread: Welcome
Second Thread: Hello
Third Thread: Welcome
Third Thread: Welcome
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