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) - 自学精灵

相关推荐
小bo波1 小时前
使用Thread子类创建线程 VS 使用Runnable接口创建线程的区别
java·多线程·thread·并发编程·runnable
SamDeepThinking1 小时前
高并发场景下,CompletableFuture与ForkJoinPool该如何取舍?
java·后端·面试
张不才4 小时前
CPU 100% 了怎么办?Java 性能排障的标准化操作
java·后端
shepherd1116 小时前
吞吐量提升 10 倍:高并发大批量数据处理任务的架构演进与性能调优
java·后端·架构
plainGeekDev9 小时前
单例模式 → object 声明
android·java·kotlin
用户298698530149 小时前
Java 实现 Word 文档文本与图片提取的方法
java·后端
SimonKing10 小时前
铁子,IntelliJ IDEA 2026.1.3来了,升不升?
java·后端·程序员
咖啡八杯21 小时前
GoF设计模式——策略模式
java·后端·spring·设计模式
用户128526116021 天前
我把祖传Java项目重构后,接口响应从3s砍到了200ms,只改了这几行代码
java