Java uses thread to represent threads, and all thread objects must be instances of the thread class or its subclasses. The role of each thread is to execute a program flow (accomplish a certain task).
Java uses the thread execution body to represent this program flow.
1. Inheriting the thread class to create a threading class
Package Org.apache;public class ThreadDemo1 extends thread {private int i;/* * Overrides the Run method, which is the thread execution body * When the thread class inherits the threads class, use this immediately Can get the current thread * Call the GetName () method directly to return the name of the current thread */public void run () {for (; i<100;i++) {System.out.println (GetName () + "" + i);}} public static void Main (string[] args) {for (int i=0;i<100;i++) {System.out.println (Thread.CurrentThread (). GetName ( + "" +i), if (i==20) {//creates and starts the first thread new ThreadDemo1 (). Start ();//Create and start the second thread new ThreadDemo1 (). Start ();}}}
Execution Result:
Note: The program actually has three threads, and the main () method is the main thread, which shows the creation of two child threads.
The values of Thread-0 and Thread-1 I are discontinuous, so Thread-0 and Thread-1 cannot share instance variables of the thread class.
2. Implement the Runnable interface to create a threading class
Package Org.apache;public class ThreadDemo2 implements Runnable {private int i;//must be Runnable when implementing Thread.CurrentThread interface (). GetName () Gets the current thread, public void, run () {for (; i<100;i++) {System.out.println (Thread.CurrentThread (). GetName () + "" "+ i) ;}} public static void Main (string[] args) {for (int i=0;i<100;i++) {System.out.println (Thread.CurrentThread (). GetName ( ) + "" +i), if (i==20) {ThreadDemo2 td = New ThreadDemo2 ();//Create thread new threads (TD, "Thread 1") through the new Thread (Target,name) method. Start (); New Thread (TD, "Thread 2"). Start ();}}}
Results:
The value of I is continuous, sharing an instance variable of the same thread class (actually the target class of the thread)
Multithreading in Java