Wednesday, June 2, 2021

Programs for creating multiple threads a) Using Thread class b) Runnable Interface.

1.  Using Thread class

PROGRAM :

package com.company;

class FirstThread extends Thread

{

    public void run()

    {

        for (int i=1; i<=10; i++)

        {

            System.out.println( "Message from First Thread : " +i);

            try

            {

                Thread.sleep(1000);

            }

            catch (InterruptedException interruptedException)

            {

            System.out.println(  "First Thread is interrupted when it is  sleeping" +interruptedException);

            }

        }

    }

}

class SecondThread extends Thread

{

    public void run()

    {

        for (int i=1; i<=10; i++)

        {

            System.out.println( "Message from Second Thread : " +i);

            try

            {

                Thread.sleep (1000);

            }

            catch (InterruptedException interruptedException)

            {

                System.out.println( "Second Thread is interrupted when it is sleeping" +interruptedException);

            }

        }

    }

}

public class ThreadDemo1

{

    public static void main(String[] args)

    {

        FirstThread firstThread = new FirstThread();

        SecondThread secondThread = new SecondThread();

        firstThread.start();

        secondThread.start();

    }

} 

OUTPUT :




1.     2. Runnable Interface

PROGRAM :

package com.company;

class MyThread implements Runnable

{

        String name;

        Thread t;

        MyThread (String thread)

        {

            name = thread;

            t = new Thread(this, name);

            System.out.println("New thread: " + t);

            t.start();

        }

 

        public void run()

        {

            try

            {

                for(int i = 5; i> 0; i--)

                {

                  System.out.println(name + ": " + i);

                  Thread.sleep(1000);

                }

            }

            catch (InterruptedException e)

            {

                System.out.println(name + "Interrupted");

            }

            System.out.println(name + " exiting.");

        }

}

 

class ThreadDemo2

{

    public static void main(String[] args)

    {

        new MyThread("One");

        new MyThread("Two");

        new MyThread("Three");

        try

        {

            Thread.sleep(10000);

        }

        catch (InterruptedException e)

        {

            System.out.println("Main thread Interrupted");

        }

        System.out.println("Main thread exiting.");

    }

}

 

OUTPUT :



Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home