Java thread Creation
There are two ways to create a Thread in Java: one is to inherit the Thread class to create a Thread object (the Thread class also implements the Runnable interface), and the other is to implement the Runnable interface. The code for the first method is as follows:
Public class MyThread extends Thread {@ Override public void run () {// task to be completed by this Thread }}
After defining the threadMyThread thread = new MyThread ();To create a thread.Thread. start ();To start the thread.
In this way, you can add other attributes for the thread in the MyThread class, such as the thread name. However, Java is a single inheritance. If your primary class still needs to inherit other parent classes, this method is not suitable.
Let's look at the second method to create a thread:
Implement the Runnable interface. The Runnable interface has only one run method. When a class implements the Runnable interface, it must implement the run () method in the class. The run () method completes the functions completed by a specific thread.
The code snippet is as follows:
Public class MyThread2 implements Runnable {@ Override public void run () {// task to be completed by the thread }}