--- way to create multi-threaded inherited Thread and implement Runnable

Thread class inherits create multi-threaded

. 1  Package cn.ftf.thread;
 2  / ** 
. 3  * multithreaded implementation inheritance Thread a multi-threaded, inheritance Thread, override the run method
 . 4  * @author house fly Ting
 . 5  *
 . 6   * / 
. 7  public  class StartThread the extends Thread {     // object inherits the thread 
. 8      public  static  void main (String [] args) {
 . 9          StartThread ST = new new StartThread ();   // instantiate the object 
10          st.start ();   // start by the start method multithreaded subobject 
11          
12          for (int I = 0; I <20 is; I ++ ) {
 13 is              System.out.println ( "side Coding" );
 14          }
 15      }
 16      public  void RUN () {   // RUN method of rewriting object 
. 17          for ( int I = 0; I <20; I ++ ) {
 18 is              System.out.println ( "while listening to music" );
 19          }
 20      }
 21 }

Implement Runnable interface to create multiple threads

. 1  Package cn.ftf.thread;
 2  / ** 
. 3  * Multiple Threads way: to achieve the Runnable, a method override run
 4  * to avoid the limitations of single inheritance, facilitate sharing resources
 . 5  * @author house fly ting
 6  *
 7   * / 
. 8  public  class StartRun the implements the Runnable {
 . 9      
10      public  static  void main (String [] args) {
 . 11          / * 
12 is          // implemented method
 13 is          StartRun StartRun new new ST = (); // Create a class object implement
 14          the Thread the Thread new new T = ( st); // create a proxy class object
 15          t.start (); // start
16          * / 
. 17          
18 is          // or simple write, anonymous, three as a 
. 19          new new the Thread ( new new StartRun ()) Start ();.
 20 is          
21 is          for ( int I = 0; I <20 is; I ++ ) {
 22 is              the System. out.println ( "side Coding" );
 23 is      }
 24  }
 25      @Override
 26 is      public  void RUN () {
 27          for ( int I = 0; I <20 is; I ++ ) {
 28              System.out.println ( "listen to songs " );
 29          }
 30          
31 is      }
32 
33 }

Implement Runnable relative to inherit the Thread class, the situation is the same for multiple threads working on the same resource (such as a grab votes), and avoid the limitations caused by the inheritance of a single Java.

Practical applications, case create multiple threads that implement runnable interface way more common than the inherited class Thread

Guess you like

Origin www.cnblogs.com/fangtingfei/p/11247510.html