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

相关推荐
步行cgn4 小时前
Spring 全注解开发详解
java·后端·spring
长河4 小时前
Java的GC(垃圾回收)中,标记无用对象的核心方法是可达性分析算法
java·jvm·算法
code2cat4 小时前
Java进阶篇之LongAdder:把统计更新分散,再读取总和
java·并发编程·原子类·longadder
凯哥Java4 小时前
写代码怎么避免逻辑漏洞?
java·开发语言·人工智能·自动化
Ivanqhz5 小时前
正余弦位置编码(Sinusoidal Positional Encoding)
java·linux·数据库
BD_Marathon5 小时前
消息对象中字段的说明
java·前端·python
zlpzlpzyd5 小时前
nacos的openapi地址
java
落魄实习生6 小时前
Agent Scope Java 2.x 系列【10】Middleware
java·开发语言·ai
ZealSinger7 小时前
Spring7 RestTemplate弃用迁移
java·spring·后端开发·restclient
朝朝辞暮i7 小时前
C++ 第 13 课:值传递 —— 为什么函数里改了,外面却没变?
java·c++·算法