简述创建多线程的两种方式
时间: 2023-08-05 15:45:17 浏览: 52
创建多线程有两种方式:继承Thread类和实现Runnable接口。
1. 继承Thread类:继承Thread类并重写run()方法,该方法是线程的执行体。然后创建Thread类的实例对象,并调用start()方法启动线程。例如:
```java
class MyThread extends Thread {
public void run() {
// 线程执行体
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
```
2. 实现Runnable接口:实现Runnable接口并实现run()方法,创建Thread类的实例对象并将其传入Runnable接口的实现类,最后调用start()方法启动线程。例如:
```java
class MyRunnable implements Runnable {
public void run() {
// 线程执行体
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 启动线程
}
}
```
这两种方式都可以创建多线程,但是实现Runnable接口的方式更加灵活,因为Java只支持单继承,而实现Runnable接口可以避免这个限制。