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

相关推荐
2601_963869951 小时前
【计算机毕业设计】基于 Spring Boot+Vue的手工体验馆管理系统的设计与实现
java·spring boot·后端
曹牧2 小时前
Java:BeanListHandler
java·数据库·oracle
白鸽(二般)8 小时前
MinIO Java Client API
java·开发语言
软萌萌的19 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
IT小盘10 小时前
13-企业Prompt模板-角色任务约束与输出格式
java·前端·prompt
爱敲键盘的猴子10 小时前
Java并发编程 -- volatile
java·java并发
plainGeekDev11 小时前
工厂模式 → Hilt
android·java·kotlin
plainGeekDev12 小时前
Application 单例 → Hilt Singleton
android·java·kotlin
888CC++12 小时前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++
学者猫头鹰13 小时前
分布式事务实战教程
java·分布式