当前位置: 首页 > article >正文

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

文章目录

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

1. 继承Thread类

示例:

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接口

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. 匿名内部类

示例:

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表达式

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

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)

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

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。
在这里插入图片描述


http://www.kler.cn/a/548810.html

相关文章:

  • 数据仓库与数据湖的协同工作:智慧数据管理的双引擎
  • 【Linux系统编程】进程概念
  • Redis 主从复制的核心原理
  • pnpm和npm安装TailwindCss
  • 【人工智能】深度学习中的梯度检查:原理详解与Python实现
  • Leetcode Hot100 第30题 416.分割等和子集
  • InnoDB如何解决幻读?深入解析MySQL的并发控制机制
  • dify新版,chatflow对deepseek的适配情况
  • 72.git指南(简单)
  • HTTP
  • cmake Qt Mingw windows构建
  • 物联网 网络安全 概述
  • 杜绝遛狗不牵绳,AI技术助力智慧城市宠物管理
  • 介绍两本学习智谱大模型的入门图书
  • 大数据实训室解决方案(2025年最新版)
  • 小米14 机型工程固件预览 刷写以及更改参数步骤 nv.img的写入
  • 【Bluedroid】 BLE连接源码分析(一)
  • LeetCode每日精进:203.移除链表元素
  • 开发中需要使用到volatile的情况
  • 【大模型系列】入门常识备忘