Monday, December 19, 2016

Write a JAVA program to illustrate creation of threads using runnable class.(start method start each of the newly created thread. Inside the run method there is sleep() for suspend the thread for 500 milliseconds).

Aim: Write a JAVA program to illustrate creation of threads using runnable class.(start method start each of the newly created thread. Inside the run method there is sleep() for suspend the thread for 500 milliseconds).

Program:

class FirstThread implements Runnable
{


  public void run()
  {

 
    for ( int i=1; i<=10; i++)
    {
     
        System.out.println( "Messag from First Thread : " +i);
  try
{

        Thread.sleep (500);
}
catch(InterruptedException interruptedException)
        {
         
            System.out.println( "First Thread is interrupted when it is sleeping" +interruptedException);
        }
    }
  }
}
class SecondThread implements Runnable
{

   SecondThread()
   {
Thread t=new Thread(this);
t.start();
   }
   public void run()
   {

   
      for ( int i=1; i<=10; i++)
      {
         System.out.println( "Messag from Second Thread : " +i);

         try
         {
             Thread.sleep(500);
         }
         catch (InterruptedException interruptedException)
         {
         
             System.out.println( "Second Thread is interrupted when it is sleeping" +interruptedException);
         }
      }
    }
}
public class ThreadDemo
{
     public static void main(String args[])
     {
        FirstThread   firstThread = new FirstThread();
        Thread thread1 = new Thread(firstThread);
        thread1.start();
SecondThread   secondThread = new SecondThread();
       }
}
Output:


Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home