How to implement threads in Java?
In Java, threads can be implemented in two ways:
- Inheriting from the Thread class:
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程运行中");
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 启动线程
}
}
- Implementing the Runnable interface.
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程运行中");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}
Whether you inherit the Thread class or implement the Runnable interface, you need to override the run() method to define the code that the thread will execute. Then create a thread object and start the thread by calling the start() method.