How to define threads in Java?
There are two ways to define threads in Java.
- Extend the Thread class by creating a custom class that inherits from it and overrides its run() method. Define the thread’s task logic within the run() method.
public class MyThread extends Thread {
public void run() {
// 定义线程的任务逻辑
}
}
- Implementing the Runnable interface: Create a class that implements the Runnable interface and implements its run() method. Then create a Thread object and pass an instance of this implementing class as a parameter to the Thread constructor.
public class MyRunnable implements Runnable {
public void run() {
// 定义线程的任务逻辑
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
Both methods can be used to create threads, with the main difference being that extending the Thread class can only inherit one class, while implementing the Runnable interface allows for implementing multiple interfaces, thus it is recommended to create threads using the Runnable interface.