用java实现多线程工作
时间: 2023-10-01 17:09:25 浏览: 51
1. 继承Thread类
```java
public class MyThread extends Thread {
@Override
public void run() {
// 执行多线程操作
}
}
```
使用:
```java
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
```
2. 实现Runnable接口
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
// 执行多线程操作
}
}
```
使用:
```java
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
```
3. 使用线程池
```java
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
@Override
public void run() {
// 执行多线程操作
}
});
executor.execute(new Runnable() {
@Override
public void run() {
// 执行多线程操作
}
});
executor.shutdown();
```
以上三种方法都可以实现多线程工作,推荐使用第二种方法实现Runnable接口,因为这种方法可以继承其他类,而继承Thread类的方式只能继承一个类。同时,使用线程池可以更好地管理线程。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)