Java并发编程——线程创建的四种方式

文章目录

  • [1. 继承Thread类](#1. 继承Thread类)
  • [2. 实现Runnable接口](#2. 实现Runnable接口)
  • [3. 匿名内部类](#3. 匿名内部类)
  • [4. lambda表达式](#4. lambda表达式)
  • [5. 实现Callable接口](#5. 实现Callable接口)
  • [6. 使用线程池(ExecutorService)](#6. 使用线程池(ExecutorService))

1. 继承Thread类

示例:

java 复制代码
public class myThread extends Thread {
    public static void main(String[] args) {
        myThread thread = new myThread();
        thread.start();
    }
    @Override
    public void run() {
        System.out.println("这是通过继承Thread类创建的线程:"+Thread.currentThread().getName());
    }
}

输出:

重写的是run()方法,而不是start()方法,但是占用了继承的名额,java中的类是单继承的。

底层也是实现Runable接口,如下图:

2. 实现Runnable接口

java 复制代码
public class myRunnable implements Runnable {
    public static void main(String[] args) {
        Thread thread = new Thread(new myRunnable());
        thread.start();
    }

    public void run() {
        System.out.println("这是通过实现Runnable接口创建的线程:"+Thread.currentThread().getName());
    }
}

总结:实现Runnable接口,实现run()方法,使用依然要用到Thread,这种方式更常用

有时候,我们会直接使用匿名内部类的方式或者Lambda表达式的方式:

3. 匿名内部类

示例:

java 复制代码
public class myThread{
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                System.out.println("这是通过使用匿名内部类创建的线程:"+Thread.currentThread().getName());
            }
        });
        thread.start();
    }
}

输出:

4. lambda表达式

java 复制代码
public class myThread{
    public static void main(String[] args) {
        Thread thread = new Thread(() -> System.out.println("这是通过使用lambda表达式创建的线程:"+Thread.currentThread().getName()));
        thread.start();
    }
}

输出:

5. 实现Callable接口

结合FutureTask

java 复制代码
class MyCallable implements Callable<Integer> {
    public Integer call() {
        System.out.println("Thread is running: " + Thread.currentThread().getName());
        return 42; // 返回值
}
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable callable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        new Thread(futureTask).start(); // 启动线程

        Integer result = futureTask.get(); // 获取返回值
        System.out.println("Result: " + result);
    }
}

输出:

FutureTask 本质上还是继承了Runnable接口

Java中,类和类是单继承的,接口之间是多继承的

6. 使用线程池(ExecutorService)

线程池是一种更高效、更灵活的线程管理方式,可以复用线程,避免频繁创建和销毁线程的开销。

java 复制代码
public class MyThread implements Runnable {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(new MyThread());
    }
    @Override
    public void run() {
        System.out.println("hello guys!");
    }
}

输出:

实现Callable接口或者Runnable接口都可以,由ExecutorService来创建线程。

以上几种方式,底层都是基于Runnable。

相关推荐
我喜欢就喜欢6 分钟前
RapidFuzz-CPP:高效字符串相似度计算的C++利器
开发语言·c++
莫彩9 分钟前
【Modern C++ Part7】_创建对象时使用()和{}的区别
开发语言·c++
经典199213 分钟前
spring boot 详解以及原理
java·spring boot·后端
星光542214 分钟前
飞算JavaAI:给Java开发装上“智能引擎”的超级助手
java·开发语言
June bug42 分钟前
【Python基础】变量、运算与内存管理全解析
开发语言·python·职场和发展·测试
醇醛酸醚酮酯43 分钟前
Qt项目锻炼——TODO(五)
开发语言·qt
学习3人组43 分钟前
JVM GC长暂停问题排查
java
R_AirMan1 小时前
深入浅出Redis:一文掌握Redis底层数据结构与实现原理
java·数据结构·数据库·redis
蹦蹦跳跳真可爱5891 小时前
Python----OpenCV(几何变换--图像平移、图像旋转、放射变换、图像缩放、透视变换)
开发语言·人工智能·python·opencv·计算机视觉
骁的小小站1 小时前
HDLBits刷题笔记和一些拓展知识(十一)
开发语言·经验分享·笔记·其他·fpga开发