在Java中实现多线程主要有两种方法:
继承Thread类并重写run()方法
```java
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行的任务
System.out.println("Thread is running.");
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现Runnable接口
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的任务
System.out.println("Thread is running.");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
注意:
继承Thread类的方法不支持代码复用,因为每个子类只能有一个父类。
实现Runnable接口的方法支持代码复用,因为可以实现多个Runnable接口的类。
两种方法都可以通过调用`start()`方法来启动线程,启动后,线程会自动调用`run()`方法。
如果需要在线程中返回值或抛出受检异常,应使用实现`Callable`接口,而不是`Runnable`接口。
请根据具体需求选择合适的方法实现多线程