1: Inheriting the Therad class
2: Implement Runnable interface
1, inherit the thread class to realize multithreading
Methods of inheriting the thread class although I am listed as a multithreaded implementation, thread is essentially an instance of implementing the Runnable interface, which represents an instance of a thread, and the only way to start a thread is through the start () instance method of the thread class. The start () method is a native method that starts a new thread and executes the run () method. This way of implementing multithreading is simple, by extend thread directly through your own class, and by copying the run () method, you can start a new thread and execute your own defined run () method. For example:
Public class extends Thread { publicvoid run () {System.out.println ("Mythread.run ()"); }}
Start the thread in the appropriate place as follows:
Newnew MyThread (); Mythread1.start (); Mythread2.start ();
2, realize the Runnable interface way to realize multithreading
If your class already extends another class, you cannot directly extends the Thread, at which point you must implement a runnable interface, as follows:
Public class extends Implements Runnable { publicvoid run () {System.out.println ("Mythread.run ()"); }}
In order to start mythread, you need to instantiate a thread first and pass in your own Mythread instance:
Newnew Thread (myThread); Thread.Start ();
In fact, when a runnable target parameter is passed to thread, the thread's Run () method calls Target.run (), referencing the JDK source code:
Public void run () { ifnull) {target.run (); }}
Two ways to implement multithreading in Java