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]
相关推荐
打工仔折腾 AI9 小时前
工业场景下时序库与实时计算一体化架构选型实践对比
java·开发语言·后端·python·性能优化·架构·ai agent 实战
蜗牛互联网9 小时前
长任务多Agent共享文件系统的Manifest交接模式
java·人工智能·后端
苏supper11 小时前
Spring Boot多环境配置与打包运行
spring boot·后端·spring
geovindu11 小时前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
SearchMan12 小时前
还有人不知道&和&&的区别?
后端
想用offer打牌12 小时前
Personal Agent爆火 - 它到底是个什么
人工智能·后端·ai编程
IT_陈寒12 小时前
Vue的v-if和v-for混用居然是个天坑
前端·人工智能·后端
打工仔折腾 AI14 小时前
从Attention到BERT:双向预训练语言模型到底解决了什么问题
人工智能·后端·python·深度学习·语言模型·bert
lizhongxuan15 小时前
Agent Sandbox: Firecracker 任务生命周期
后端
YYYing.15 小时前
【设计模式系列 (七) 】桥接模式
c++·后端·设计模式·桥接模式