A total of two methods the thread class and the Runnable interface, in contrast, tend to use runnable
Because a class can implement multiple interfaces, but can only inherit one class, it is relatively inclined to use runnable
The first method: use thread
is actually the way to inherit and rewrite the parent thread.
The basic idea is still Java's inherited polymorphic thought
The first is to write a class yourself, inherit the thread class, and rewrite the Run () method
Then implement the class that you write in the calling function, calling the Star () method
Note: Call the start () method to implement multi-threaded, call the Run () method, which is single-threaded
public class Firstthread extends thread{public void Run () {for (int i=1;i<100;i++) {System.out.println ("first thread-- > "+i);}}}
public class Main {public static void main (string[] args) {firstthread ft=new firstthread (), Ft.start (); for (int i=0;i<1 00;i++) {System.out.println ("main-->" +i);}}}
The second method: use runnable
is actually the implementation of the interface runnable
First realize the class that you write,
The thread object is then generated and the interface object as a parameter
Last start thread
Note: Call the start () method to implement multi-threaded, call the Run () method, which is single-threaded
public class Runable implements Runnable {@Overridepublic void Run () {for (int i=1;i<100;i++) {System.out.println (" First runnable--> "+i);}}}
public class Main {public static void main (string[] args) {//Implement Interface runable ra=new runable ();//Generate Thread object and interface object as parameter thread t =new thread (RA);//Start multithreaded T.start (); for (int i=0;i<100;i++) {System.out.println ("main-->" +i);}}}
Implementation of Java Threads