create thread in java with example

create thread in java with example

6 (b) Aim: To Write a Java program that creates 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

Description :

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. The technique used to implement threads here is by extending Thread class.

While executing a thread, if any interrupt occurs then there arises a java exception. In such cases, to handle these exceptions thread statements are kept in try-catch blocks.

Source code :

import java.io.*;

class A extends Thread

{

            String name;

            A(String tname)

            {

                        name=tname;

                        System.out.println(name);

            }

            public void run()

            {

                        System.out.println(name);

            }

}

class HelloThread

{

            public static void main(String ar[])

            {

                        A obj1= new A(“Good Morning”);

                        try

                        {

                                    Thread.sleep(1000);

                        }

                        catch(Exception ie)

                        {

                                    System.out.println(“Interrupted”);

                        }

                        A obj2= new A(“Hello”);

                        try

                        {

                                    Thread.sleep(1000);

                        }

                        catch(Exception ie)

                        {

                                    System.out.println(“Interrupted”);

                        }

                        A obj3= new A(“Welcome”);

                        try

                        {

                                    Thread.sleep(1000);

                        }

                        catch(Exception ie)

                        {

                                    System.out.println(“Interrupted”);

                        }

            }

}

Sample output :

GoodMorning

Hello

Welcome

create thread in java with example

Leave a Comment

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