There are 2 ways to implement Multithreading in Java: 1 to extend the Java.lang.Thread class; 2 to implement the Java.lang.Runnable interface
Here is an example of implementing runnable to implement multithreading
Public classDoSomethingImplementsRunnable {//implementing the Runnable interface Public voidRun () {//implementing the Run method for(inti = 0; I < 5; i++) {//Repeat 5 timesSYSTEM.OUT.PRINTLN ("Secondary thread do something"); Try{Thread.Sleep (1000);//Sleep 1 seconds}Catch(Exception e) {}}} Public Static voidMain (string[] args) {dosomething dothing=Newdosomething (); Thread T1=NewThread (dothing); T1.start (); //Here is the question raised by the landlord, start the thread, execute the above write the run () method for(inti = 0; I < 5; i++) {//Main ThreadSystem.out.println ("Main thread do something"); Try{Thread.Sleep (1000);//Sleep 1 seconds}Catch(Exception e) {} }}}
The second Kind
New Thread (new Runnable () { publicvoid run () { System.out.println ( "Start data Run ..."); System.out.println ("Stop data Run ..."); } ); T1.start ();
java-to open a new thread