Creation and initiation of threads
The Java language has built-in multithreaded support, and all classes that implement the Runnable interface can be started with a new thread that executes the run () method of the instance, and the thread ends when the run () method finishes executing. Once a thread has finished executing, the instance can no longer be restarted, only a new instance can be rebuilt, and a new thread is started.
The thread class is an instance of the Runnable interface that represents an instance of a thread, and the only way to start a thread is through the thread class's start () instance method:
Thread t = new Thread();
t.start();
The start () method is a native method that starts a new thread and executes the run () method. The thread class default run () method quits without doing anything. Note: Calling the run () method directly does not start a new thread, it is no different from calling a normal Java method.
Therefore, there are two ways to implement your own thread:
Method 1: Your own class extend thread, and the copy run () method, you can start a new thread and execute your own defined run () method. For example:
public class MyThread extends Thread {
public run() {
System.out.println("MyThread.run()");
}
}
Start the thread in the right place: New Mythread (). Start ();
Method 2: If your class is already extends another class, you cannot extends Thread directly, at which point you must implement a runnable interface:
public class MyThread extends OtherClass implements Runnable {
public run() {
System.out.println("MyThread.run() ");
}
}
In order to start mythread, you need to instantiate a thread first and pass in your own Mythread instance:
MyThread myt = new MyThread();
Thread t = new Thread (myt);
t.start();