Anonymous inner class creates a thread, the thread is created to simplify the code

1  Package Penalty for cn.learn.thread.Thread;
 2  / * 
3      create anonymous inner classes to implement threads of the way
 4  
5      anonymous: no name
 6      internal class: write inside other classes
 7  
8      Role: simplify the code, do not write a single class, to set threading task
 9         handle class inherits the parent class, override the parent class method, create a subclass object to complete the synthesis of a
 10         or implementation class implement an interface, rewritten interface methods to create a complete implementation class objects
 11         anonymous inner the final product class: the child class / class object implement, no name
 12 is  
13 is      the format:
 14          new new parent class / interface {
 15              override the parent class / interface method
 16          }
 . 17  
18 is   * / 
. 19  public  class InnerClassThread {
 20 is      public static  void main (String [] args) {
 21 is          // known parent thread is Thread, derived class 
22 is          new new the Thread ( "Thread 1" ) {
 23              // override method provided the thread run task 
24  
25              @Override
 26 is              public  void RUN () {
 27                  for ( int I = 0; I <20 is; I ++ ) {
 28                      System.out.println (Thread.currentThread () getName ().);
 29  
30                  }
 31 is              }
 32          } .start (); / / open thread
 33 is  
34 is  
35          @Implement the interface, new new polymorphic = RunnableImpl runnableThread the Runnable (); 
36          the Runnable run = new new the Runnable () {
 37 [              // override the run method, set the task thread 
38 is              @Override
 39              public  void run () {
 40                  for ( int I = 0 ; I <20 is; I ++ ) {
 41 is                      System.out.println (Thread.currentThread () getName ());.
 42 is                  }
 43 is              }
 44 is          };
 45          // open multithreading class name set 
46 is          new new the thread (RUN , "two threads" ) .start ();
 47  
48         // The code further simplify 
49          new new the Thread ( new new the Runnable () {
 50              // override the run method, set the task thread 
51 is              @Override
 52 is              public  void run () {
 53 is                  for ( int I = 0; I <20 is; I ++ ) {
 54 is                      System.out.println (Thread.currentThread () getName ().);
 55                  }
 56 is              }
 57 is          }, "three threads" ) .start ();
 58  
59      }
 60 }

 

Guess you like

Origin www.cnblogs.com/huxiaobai/p/11519676.html