Sunday, November 19, 2017

LAB 14 - THREAD IMPLEMENTATION (RUNNABLE)

Example:
public class MyThread implements Runnable {
   public void run(){ 
     System.out.println("THREAD IS RUNNING USING RUNNABLE INTERFACE."); 
   } 
   public static void main(String[] args) {
     Thread t = new Thread(new MyThread());
     t.start();
} }
Example 2:
class Count implements Runnable
{
   Thread mythread ;
   Count()
   {
      mythread = new Thread(this, "my runnable thread");
      System.out.println("my thread created" + mythread);
      mythread.start();
   }
   public void run()
   {
      try
      {
        for (int i=0 ;i<5;i++)
        {
          System.out.println("Printing the count " + i);
          Thread.sleep(1000);
        }
     }
     catch(InterruptedException e)
     {
        System.out.println("my thread interrupted");
     }
     System.out.println("mythread run is over" );
   }
}
class MyThread
{
    public static void main(String args[])
    {
       Count cnt = new Count();
       try
       {
          while(cnt.mythread.isAlive())
          {
            System.out.println("Main thread will be alive till the child thread is live");
            Thread.sleep(1500);
          }
       }
       catch(InterruptedException e)
       {
          System.out.println("Main thread interrupted");
       }
       System.out.println("Main thread run is over" );
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.