3.How to create Threads by implementing Runnable interface in Java

 class newThread implements Runnable // Runnable inter face   
 {  
      Thread t;  
      newThread()  
      {  
           t= new Thread(this,"Demo: ");   
           System.out.println("Child Thread: "+t);  
           t.start();   
      }  
 public void run() {  
    try {  
      for(int i = 10; i > 0; i--) {  
       System.out.println("Child Thread: " + i);  
       // Let the thread sleep for a while.  
       Thread.sleep(500);  
      }  
    } catch (InterruptedException e) {  
      System.out.println("Child interrupted.");  
    }  
    System.out.println("Exiting child thread.");  
   }  
 }  
 public class myExtend  
 {  
      public static void main(String args[])  
      {  
           new newThread(); // create a new thread  
    try {  
      for(int i = 7; i > 0; i--) {  
       System.out.println("Main Thread: " + i);  
       Thread.sleep(1000);//it throws Interrupted Execution Exception..  
      }  
    } catch (InterruptedException e) {  
      System.out.println("Main thread interrupted.");  
    }  
    System.out.println("Main thread exiting.");  
      }  
 }  

Post a Comment

0 Comments