In Java to implement multithreading, there are two ways, one is to inherit the thread class, the other is to implement the Runable interface.
For the direct inheritance of the thread class, the code's general framework is:
Class Name extends thread{
Method 1;
Method 2;
...
public void Run () {
Other code ...
}
Property 1;
Property 2;
...
}
Here's a simple little example to help you understand
clock output every 1s time:
Import Java.util.Date;
public class Clockthreadtest {
public static void Main (string[] args) {
Clockthread clockthread=new Clockthread ();
Clockthread.start ();
System.out.println ("End");
}
}
Class Clockthread extends thread{
@Override
public void Run () {
Super.run ();
while (true) {
System.out.println (New Date ());
try {
Thread.Sleep (1000);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}
The output results show:
....
The endless downward output ....
Note: While we are calling here the start () method, we actually call the body of the run () method.
So: Why can't we just call the run () method directly?
My understanding is that the operation of the thread requires the support of the local operating system.
But this method has its drawbacks, for example, clockthread if there are other parent classes, then this method can not be used. Because it is not allowed to have several parent classes at the same time in Java. The next method is described below:
By implementing the Runnable interface, the general framework is:
Class name implements Runnable{
Method 1;
Method 2;
...
public void Run () {
Other code ...
}
Property 1;
Property 2;
...
}