Java线程的三种创建方式

java线程创建的三种方式为:

1.继承Thread类

scala 复制代码
class MyThread extends Thread {

    public void run() {
        // 线程执行的代码
    }

}
// 使用
MyThread thread = new MyThread();
thread.start();`

实现runable接口

arduino 复制代码
`class MyRunnable implements Runnable {
    public void run() {
        // 线程执行的代码
    }
}

// 使用
Thread thread = new Thread(new MyRunnable());
thread.start();`

实现callable接口

arduino 复制代码
class MyCallable implements Callable<String> {
    public String call() throws Exception {
        // 线程执行的代码
        return "结果";
    }
}

// 使用
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
String result = future.get(); // 获取返回值
executor.shutdown();

三种方法的演变关系是依次的,thread类最早,runable接口次之,callable接口最晚,其中callable接口提供了执行完成后提供返回值的能力,通常推荐的是使用继承runnable接口的方式,如果需要使用返回值,则使用callable接口。

graph TD A[需要创建线程] --> B{需要返回值或异常处理?} B -->|是| C[使用Callable+Future] B -->|否| D{类需要继承其他类吗?} D -->|是| E[实现Runnable] D -->|否| F{简单临时使用?} F -->|是| G[继承Thread] F -->|否| H[实现Runnable]
相关推荐
新知图书11 小时前
搭建Spring Boot开发环境
java·spring boot·后端
宸津-代码粉碎机11 小时前
Spring Boot 4.0虚拟线程实战调优技巧,最大化发挥并发优势
java·人工智能·spring boot·后端·python
小码哥_常11 小时前
一个Starter搞定六种防护,Spring Boot API的超强护盾来了
后端
小村儿13 小时前
连载04-最重要的Skill---一起吃透 Claude Code,告别 AI coding 迷茫
前端·后端·ai编程
IT_陈寒14 小时前
Vite的alias配置把我整不会了,原来是这个坑
前端·人工智能·后端
gelald14 小时前
Spring Boot - 自动配置原理
java·spring boot·后端
希望永不加班15 小时前
SpringBoot 集成测试:@SpringBootTest 与 MockMvc
java·spring boot·后端·log4j·集成测试
uzong15 小时前
软件人员可以关注的 Skill,亲测确实不错,值得试一下
人工智能·后端
掘金虾15 小时前
Hono 框架入门到实战:用 Node.js 写一个支持工具调用的流式对话 Agent
后端
用户83562907805115 小时前
Python 自动拆分 Word 文档教程:按分节符与分页符处理
后端·python