Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Java » Programs » Threads » Java program that creates three threads
Suryateja Pericherla Categories: Threads. No Comments on Java program that creates three threads
3.9
(7)

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

 


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory