Java uses the thread class to represent threads, and all thread objects must be instances of the thread class or its subclasses. The function of each thread is to accomplish a certain task, which is to execute a program flow (a sequence of code execution). Java uses the thread execution body to represent this stream of programs.
public class Firstthread extends Thread {
private int i;
@Override
//Rewrite the Run method, the method body of the Run method is the thread execution body public
void Run () {
System.out.println ("Hello," +getname () + "" + i);
}
public static void Main (string[] args) throws exception{
for (int i = 0; i < i++) {
//Invoke thread's Currentthre The ad () method gets the current thread
System.out.println (Thread.CurrentThread (). GetName () + "" + i);
if (i==2) {
//Create and start the first thread
new Firstthread (). Start ();
Create and start the second thread
new Firstthread (). Start ();
The Firstthread class in the above program inherits the thread class and implements the Run method, the code execution flow in the Run method is the task that the thread needs to complete. Although the above program only shows the creation and launch of 2 threads, in fact the program has 3 threads, that is, the program shows the 2 child threads and the main thread created. When a Java program begins to run, the program creates at least one main thread, and the threads of the main process are determined by the main method.
When you create a thread class by using methods that inherit from the thread class, the instance variables of the thread class cannot be shared among multiple threads.