Java programs only allow single inheritance, that is, a subclass can have only one parent class. So in Java, if a class inherits a class, and when it wants to adopt multithreading technology, it cannot generate threads in the way that inherits the thread class, because Java does not allow multiple inheritance. You will use the Runnable interface to create the thread. The following are the approximate steps to implement multithreading using the Runnable interface method:
- Define a new class to implement the Runnable interface, assuming this class is named Testthread.
- Implement the Run () method in the Testthread class, which is the running program code for the new thread.
- Create an object T1 for the Testthread class, and then create an object of the thread class with the T1 parameter and call the start () method of the object.
Here is an example of implementing multithreading in this way:
public class threaddemo9_2{public static void Main (String args[]) { Testthread t = new Testthread (); New Thread (t). Start (); Loop output for (int i = 0; i < i++) { System.out.println ("Main thread is running"); }}} Class Testthread implements runnable{public void Run () {for (int i = 0; i <; i++) { Syst Em.out.println ("Testthread is Running");}}}
Why does the runnable interface also need to call the start () method in the thread class to start multithreading? By looking up the JDK document, the reader can find that there is only one run () method in the Runnable interface, and there is no start () method. So a class that implements the Runnable interface must also start multithreading with the Start () method in the thread class. This can be found by looking up the thread class in the JDK documentation, and in the thread class, there is a construction method:
Public Thread (Runnable target)
As a result of this construction method, it can be found that an instantiated object of an Runnable interface is instantiated as a parameter to instantiate the thread class object. In the actual development, we should use runnable interface to implement multithreading mechanism as far as possible.
Java Multithreading Implementation 2, implement Runnable interface