java创建多个线程
时间: 2023-11-15 09:04:15 浏览: 39
在Java中创建多个线程,可以使用Thread类或者实现Runnable接口的方式。
使用Thread类创建线程的步骤如下:
1. 定义一个类,继承自Thread类,重写run()方法:
```
public class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
```
2. 创建MyThread实例:
```
MyThread thread1 = new MyThread();
```
3. 启动线程:
```
thread1.start();
```
使用实现Runnable接口的方式创建线程的步骤如下:
1. 定义一个类,实现Runnable接口,重写run()方法:
```
public class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
```
2. 创建MyRunnable实例:
```
MyRunnable runnable1 = new MyRunnable();
```
3. 创建Thread实例,将MyRunnable实例作为参数传入:
```
Thread thread1 = new Thread(runnable1);
```
4. 启动线程:
```
thread1.start();
```
在实际应用中,可以创建多个线程,每个线程执行不同的任务。可以使用ThreadPoolExecutor类来管理多个线程,从而实现更加灵活的线程管理。