Java implementation runnable interface to create multithreading
Multiple threads are implemented by inheriting the thread class, but this approach has some limitations, because only single inheritance is supported in Java, and a class cannot inherit the thread class once it inherits a parent class
For example, the student class student inherits the person class and cannot create threads by inheriting the thread class
In this case, the thread class provides another construct method runnable target
Where runnable is an interface, it has only one run () method
When you create a thread object by using the Runnable target construction method of the thread class, you simply pass an instance object for the method that implements the Runnable interface, so that the created thread will invoke the run () method in the Runnable interface as the running code, Instead of calling the run () method in the Thread class
Example, Example03.java
public class example03{public
static void Main (string[] args) {
//Create the Mythread instance object/
/Create Thread object
//Open thread, The run () method in the execution thread
mythread mythread=new mythread ();
Thread thread=new thread (mythread);
Thread.Start ();
while (true) {
System.out.println ("main () method is running");
}} Class Mythread implements the
code snippet for the runnable{//thread, when the start () method is called, the thread begins to perform public
void run () {while
(true) {
System.out.println (The Run () method of the Mythread class is running ");}}
Compile run
Code description
Mythread class, implements the Runnable interface, and overrides the Run () method in the Runnable interface
By using the method of constructing the thread class, passing the instance object of the Mythread class as a parameter, you can see that the print statements in the main () method and the Run () method perform the