steps:
1. Define the class implementation runnable interface.
2. Overwrite the Run method in the interface. Define the thread task code in the Run method.
3. Create an object of the thread class.
4. Pass the subclass object of the Runnable interface as a parameter to the constructor of the thread class.
5. Call the Start method of the thread class to open the thread.
Instance:
classDemoImplementsrunnable{PrivateString name; PublicDemo (String name) { This. Name =name; } Public voidrun () { for(inti = 0; I < 20; i++) {System.out.println (name+ ".." + Thread.CurrentThread (). GetName () + "..." +i); }}} Public classThreadDemo2 { Public Static voidMain (string[] args) {Demo d=NewDemo ("Demo"); Thread T=NewThread (d); Thread T2=NewThread (d); T.start (); T2.start (); System.out.println (Thread.CurrentThread (). GetName ()+ "***");//The main thread executes once at the beginning and then does not execute. }}
Benefits of this approach:
1. Implementing runnable interface avoids the limitation of single inheritance, so it is more commonly used.
2. The way to implement the Runnable interface, more conform to object-oriented, the thread is divided into two parts, part of the thread object, part of the thread task.
Inherit the thread class: The Run method is in thread. The thread object and the thread task are coupled together. Once the child class object of the thread class is created, it is both a thread object and a threaded task.
Implement the Runnable interface: The Run method is in runnable. Separate the thread tasks into objects (Runnable interface types), use runnable to identify thread tasks, and thread to define threading objects. The Runnable interface decouples thread objects and thread tasks.
Create multithreaded mode two (implement Runnable interface)