Friday, September 20, 2013

JAVA: Static Nested Class and Normal Nested Class (Inner Class) example code

 

   1: package general_threadCreation;
   2:  
   3: public class CreateThread_RunnableTest 
   4: {    
   5:     // Static Nested Class
   6:     public static class MyRunnableStatic implements Runnable
   7:     {
   8:         private int runnableIdx = -1;
   9:         
  10:         public MyRunnableStatic(int p_runnableIdx)
  11:         {
  12:             this.runnableIdx = p_runnableIdx;
  13:         }
  14:  
  15:         @Override
  16:         public void run() 
  17:         {
  18:             int i = 0; 
  19:             while(true)
  20:             {
  21:                 System.out.println("Static Runnable " + this.runnableIdx + ": " + i);
  22:                 i++;
  23:             }
  24:         }        
  25:     }
  26:     
  27:     // Nested Class (Inner Class)
  28:     public class MyRunnableInner implements Runnable
  29:     {
  30:         private int runnableIdx = -1;
  31:         
  32:         public MyRunnableInner(int p_runnableIdx)
  33:         {
  34:             this.runnableIdx = p_runnableIdx;
  35:         }
  36:  
  37:         @Override
  38:         public void run() 
  39:         {
  40:             int i = 0; 
  41:             while(true)
  42:             {
  43:                 System.out.println("Inner Runnable " + this.runnableIdx + ": " + i);
  44:                 i++;
  45:             }
  46:         }        
  47:     }
  48:     
  49:     
  50:     public static void main(String[] args)
  51:     {        
  52:         // ---- Use the normal nested class (inner class)
  53:         CreateThread_RunnableTest.MyRunnableInner myRunnableInner 
  54:             = new CreateThread_RunnableTest().new MyRunnableInner(1);
  55:         //myRunnableInner.run(); // Not parallel if not putting it into a thread
  56:         Thread myRunnableInnerThread = new Thread(myRunnableInner);
  57:         myRunnableInnerThread.start();
  58:         
  59:         // ---- Use the static nested class
  60:         MyRunnableStatic myRunnableStatic = new MyRunnableStatic(2);
  61:         //myRunnableStatic.run(); //Not parallel if not putting it into a thread
  62:         Thread myRunnableStaticThread = new Thread(myRunnableStatic);
  63:         myRunnableStaticThread.start();
  64:     }
  65:  
  66: }
  67:  

No comments:

Post a Comment