Tuesday, April 21, 2015

Threads Sample Code

class RunnableDemo implements Runnable {
    //class RunnableDemo extends Thread
   private Thread t;
   private String threadName;
  
   RunnableDemo(String name){
       threadName = name;
       System.out.println("Creating " +  threadName );
   }
  
   public void start ()
   {
      System.out.println("Starting " +  threadName );
      if (t == null)
      {
         t = new Thread(this, threadName);
         t.start();
      }
   }

   public void run() {
          System.out.println("Running " +  threadName );
          try {
             for(int i = 4; i > 0; i--) {
                System.out.println("Thread: " + threadName + ", " + i);
                // Let the thread sleep for a while.
                Thread.sleep(60*1000);
             }
         } catch (InterruptedException e) {
             System.out.println("Thread " +  threadName + " interrupted.");
         }
         System.out.println("Thread " +  threadName + " exiting.");
       }
      
}



public class TestDemo {
   
    public static void main(String args[])
    {
        RunnableDemo demo = new RunnableDemo("Thread1");
       
        demo.start();
    }

}

No comments:

Post a Comment