Method 2: Implement the Runnable interface
Steps
* A: Custom class myrunnable Implementation Runnable interface
* B: Rewrite the Run () method
* C: Create an object of the Myrunnable class
* D: Create the object of the thread class and pass the C-Step object as a construction parameter
1 Public classMyrunnabledemo {2 Public Static voidMain (string[] args) {3 //to create an object of the Myrunnable class4Myrunnable my =Newmyrunnable ();5 6 //creates an object of the thread class and passes the C-step object as a construction parameter7 //Thread (Runnable target)8 //thread T1 = new Thread (my);9 //thread t2 = new Thread (my);Ten //t1.setname ("Brigitte"); One //T2.setname ("Elina"); A - //Thread (Runnable target, String name) -Thread T1 =NewThread (My,"Brigitte"); theThread t2 =NewThread (My,"Elina"); - - T1.start (); - T2.start (); + } - } + Public classMyrunnable implements Runnable { A at @Override - Public voidrun () { - for(intx =0; X < -; X + +) { - //The method of the thread class cannot be used directly because of the way the interface is implemented, but it can be used indirectly -System. out. println (Thread.CurrentThread (). GetName () +":"+x); - } in } - to}
Java Note Threading Mode 2