1.thrtest.java inheriting the thread class mode
Public classThrtestextendsThread {PrivateString name; Publicthrtest () {} Publicthrtest (String name) { This. Name =name; } Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println (name+ "Run" +i); } } Public Static voidMain (string[] args) {thrtest H1=NewThrtest ("A"); Thrtest H2=NewThrtest ("B");//H1.run ();//H2.run ();H1.start (); H2.start (); }}
2.runntest.java Implement Runnable interface mode
Public classRunntestImplementsRunnable {PrivateString name; Publicrunntest () {} Publicrunntest (String name) { This. Name =name; } Private intTicket = 5;//5 Tickets Public voidrun () { for(inti=0; i<=20; i++) { if( This. ticket > 0) {System.out.println ( This. Name + Thread.CurrentThread (). GetName () + "Selling tickets" + This. ticket--); } } } Public Static voidMain (string[] args) {runntest H1=NewRunntest ("Thread A");//resource Sharing//thread demo= New Thread (H1, "window number 1th");//thread demo1=new Thread (H1, "window number 2nd");//thread demo2=new Thread (H1, "window number 3rd");Thread Demo=NewThread (H1); Thread Demo1=NewThread (H1); Thread Demo2=NewThread (H1); Demo.start (); Demo1.start (); System.out.println ("---before thread starts" +demo2.isalive ()); Demo2.start (); System.out.println ("---After thread start" +demo2.isalive ()); }}