创建线程的四种方式
时间: 2023-07-27 07:16:35 浏览: 63
在Java中,有以下四种常见的创建线程的方式:
1. 继承Thread类并重写run()方法
```java
public class MyThread extends Thread {
@Override
public void run() {
// 该线程要执行的代码
}
}
// 启动线程
MyThread thread = new MyThread();
thread.start();
```
2. 实现Runnable接口并传入Thread类中
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
// 该线程要执行的代码
}
}
// 启动线程
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
```
3. 实现Callable接口并传入FutureTask类中
```java
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
// 该线程要执行的代码
return "result";
}
}
// 启动线程
MyCallable callable = new MyCallable();
FutureTask<String> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
// 获取线程执行结果
String result = futureTask.get();
```
4. 使用线程池创建线程
```java
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(() -> {
// 该线程要执行的代码
});
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)