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]
相关推荐
卷无止境12 小时前
LangExtract:让LLM从杂乱文本中"抠"出结构化数据的开源工具
后端·python
卷无止境13 小时前
软件复杂度:那些让代码变得难以理解的东西,到底能不能量化?
后端·python
mldong1 天前
从 mldong 到 jeeflow:一个工作流引擎的独立进化
后端
陈随易1 天前
MoonBit抓包模块pcap,查看电脑的每一次联网通信
前端·后端·程序员
Aaron - Wistron1 天前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
卷无止境1 天前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境1 天前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
IT_陈寒1 天前
Vite热更新失效?你可能漏了这个配置
前端·人工智能·后端
SomeB1oody1 天前
【RustyML入门】1.0. 快速上手
开发语言·后端·机器学习·rust·教程