Java多线程--三种写法(Thread、Runnable、Callable)

原文网址:Java多线程--三种写法(Thread、Runnable、Callable)_IT利刃出鞘的博客-CSDN博客

简介

本文介绍Java多线程的三种写法(Thread、Runnable、Callable)。

写法1:继承 Thread 类

java 复制代码
package com.example.a;

class TestThread extends Thread {
    private String name;

    public TestThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(name + "运行,i = " + i);
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        Thread thread1 = new TestThread("线程 A");
        Thread thread2 = new TestThread("线程 B");

        // 不能使用run(),因为它不会去启动多线程
        thread1.start();
        thread2.start();
    }

}

运行结果

java 复制代码
线程 A运行,i = 0
线程 B运行,i = 0
线程 A运行,i = 1
线程 B运行,i = 1
线程 B运行,i = 2
线程 B运行,i = 3
线程 B运行,i = 4
线程 B运行,i = 5
线程 B运行,i = 6
线程 B运行,i = 7
线程 B运行,i = 8
线程 A运行,i = 2
线程 A运行,i = 3
线程 B运行,i = 9
线程 A运行,i = 4
线程 A运行,i = 5
线程 A运行,i = 6
线程 A运行,i = 7
线程 A运行,i = 8
线程 A运行,i = 9

写法2:实现 Runnable 接口

实例

java 复制代码
package com.example.a;

class TestThread implements Runnable {
    private String name;

    public TestThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(name + "运行,i = " + i);
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        TestThread thread1 = new TestThread("线程 A");
        TestThread thread2 = new TestThread("线程 B");

        Thread t1 = new Thread(thread1);
        Thread t2 = new Thread(thread2);
        t1.start();
        t2.start();
    }

}

运行结果

java 复制代码
线程 B运行,i = 0
线程 B运行,i = 1
线程 A运行,i = 0
线程 B运行,i = 2
线程 B运行,i = 3
线程 B运行,i = 4
线程 B运行,i = 5
线程 B运行,i = 6
线程 B运行,i = 7
线程 A运行,i = 1
线程 A运行,i = 2
线程 A运行,i = 3
线程 A运行,i = 4
线程 A运行,i = 5
线程 A运行,i = 6
线程 A运行,i = 7
线程 A运行,i = 8
线程 A运行,i = 9
线程 B运行,i = 8
线程 B运行,i = 9

Thread类和Runnable接口的区别

上边是文章的部分内容,为统一维护,全文已转移到此网址:Java多线程-三种写法(Thread、Runnable、Callable) - 自学精灵

相关推荐
asdfg12589639 分钟前
一个例子理解Java中的函数式接口
java·函数式接口
toolsmith14 分钟前
一个商业软件的License校验,居然把验签的证书放在了License文件里
java
wuminyu16 分钟前
JDK21 FFM异步读取MSG_ZEROCOPY错误队列揭秘
java·linux·c语言·jvm·c++
存在morning22 分钟前
【PySpark 学习笔记 三】DataFrame API 入门
android·java·数据库
AC赳赳老秦24 分钟前
企业标签体系搭建:基于 OpenClaw 采集的多维度公开数据,构建企业画像标签库
java·运维·服务器·python·信息可视化·deepseek·openclaw
智嵌研习社28 分钟前
Ollama 本地大模型完全配置指南:Modelfile 参数与系统环境变量深度解析
java·开发语言
Crawl1 小时前
5.登录与分页功能分析
java·后端
今天AI了吗1 小时前
AI Agent 在数据分析领域的落地判断:哪些场景真的需要 Agent
java·数据库·人工智能·python·sql·数据分析·copilot
SimonKing1 小时前
SwitchHosts V5大改版,我发现了这些惊喜和坑
java·后端·程序员
山甫aa2 小时前
日志技术 Logback + Slf4j —— 从零开始的 Web 后端学习
java·后端·学习·web·logback