One, the first way to create a thread: Inherit the Thread class
classDemoextendsthread{@Override Public voidrun () {Super. Run (); for(inti=0;i<20;i++) System.out.println (Thread.CurrentThread ()+"...."+i); }} Public classThreadDemo1 { Public Static voidMain (string[] args) {Demo D1=NewDemo (); Demo D2=NewDemo (); D1.start (); D2.start (); }}
Second way to create a thread: Implement the Runnable interface
classDemo2Implementsrunnable{ Public voidrun () { for(inti=0;i<20;i++) System.out.println (Thread.CurrentThread ()+"..."+i); }} Public classThreadDemo2 { Public Static voidMain (string[] args) {Thread T1=NewThread (NewDemo2 ()); Thread T2=NewThread (NewDemo2 ()); T1.start (); T2.start (); }}
The advent of runnable is simply the encapsulation of the object of the thread's task.
Benefits of implementing the Runnable interface:
1. Separate the thread's tasks from the child classes of the thread for individual encapsulation. Encapsulates a task into an object based on object-oriented thinking.
2. Avoid the limitations of Java single inheritance
So the second method of creating threads is more common.
Two implementation forms of Java threads