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]
相关推荐
计算机毕设VX:Fegn089515 小时前
计算机毕业设计|基于springboot + vue汽车销售系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·汽车·课程设计
聆风吟º15 小时前
【Spring Boot 报错已解决】Spring Boot项目启动报错 “Main method not found“ 的全面分析与解决方案
android·spring boot·后端
Rover.x15 小时前
Arthas内存泄露排查
java·后端
艺杯羹15 小时前
掌握Spring Boot配置艺术:从YAML基础到实战进阶
java·spring boot·后端·yaml
喵叔哟15 小时前
12.云平台部署
后端·.netcore
rannn_11116 小时前
【SQL题解】力扣高频 SQL 50题|DAY1
后端·sql·题解
IT_陈寒16 小时前
JavaScript性能优化:7个V8引擎内部原理帮你减少90%内存泄漏的实战技巧
前端·人工智能·后端
JaguarJack16 小时前
当遇见 CatchAdmin V5-模块化设计重新定义 Laravel 后台开发
后端·php
Qiuner16 小时前
Spring Boot AOP(三) 通知执行链源码解析
java·spring boot·后端
羑悻的小杀马特16 小时前
【Linux篇章】再续传输层协议TCP:用技术隐喻重构网络世界的底层逻辑,用算法演绎‘网络因果律’的终极推演(通俗理解TCP协议,这一篇就够了)!
linux·网络·后端·tcp/ip·tcp协议