首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Java 多线程编程深入实战:从基础到线程池管理

Java 多线程编程深入实战:从基础到线程池管理

原创
作者头像
用户11690575
发布2025-06-10 22:35:35
发布2025-06-10 22:35:35
39500
代码可运行
举报
运行总次数:0
代码可运行

一、前言

多线程是 Java 的强大特性之一,它允许程序并发执行多个任务,提高资源利用率和响应能力。无论是 Web 服务、高性能计算、文件下载、图像处理,还是后台任务调度,多线程都是提升效率的利器。

本篇文章将深入介绍 Java 多线程编程,包括创建线程、同步控制、线程通信、线程池与实际案例。


二、Java 创建线程的三种方式

2.1 方式一:继承 Thread

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑public class MyThread extends Thread {
    public void run() {
        System.out.println("线程运行:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        new MyThread().start();
    }
}

🖼️ 图示:MyThreadThread → 执行 run() 方法


2.2 方式二:实现 Runnable 接口

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑public class RunnableDemo {
    public static void main(String[] args) {
        Runnable task = () -> System.out.println("Runnable 执行:" + Thread.currentThread().getName());
        new Thread(task).start();
    }
}

优点:支持多继承结构、代码更清晰。


2.3 方式三:使用 CallableFuture

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑import java.util.concurrent.*;

public class CallableDemo {
    public static void main(String[] args) throws Exception {
        Callable<String> task = () -> "返回结果:" + Thread.currentThread().getName();
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> result = executor.submit(task);

        System.out.println(result.get());
        executor.shutdown();
    }
}

三、线程的生命周期

线程状态包括:

  • NEW:创建后尚未启动
  • RUNNABLE:正在运行
  • BLOCKED:被阻塞等待锁
  • WAITING / TIMED_WAITING:等待另一个线程操作
  • TERMINATED:线程结束

🖼️ 图示:Java Thread 生命周期状态图(NEW → RUNNING → TERMINATED)


四、线程同步与互斥

4.1 synchronized 关键字

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑public synchronized void safeMethod() {
    // 线程安全代码
}

或同步代码块:

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑synchronized (this) {
    // 临界区
}

4.2 多线程卖票例子(避免超卖)

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑public class TicketSale {
    private int tickets = 10;

    public synchronized void sell(String name) {
        if (tickets > 0) {
            System.out.println(name + " 卖出一张票,剩余:" + --tickets);
        }
    }

    public static void main(String[] args) {
        TicketSale ts = new TicketSale();
        Runnable task = () -> {
            for (int i = 0; i < 5; i++) ts.sell(Thread.currentThread().getName());
        };

        new Thread(task, "窗口A").start();
        new Thread(task, "窗口B").start();
    }
}

五、线程通信机制(wait/notify)

5.1 示例:生产者-消费者模型

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑class Box {
    private int content;
    private boolean empty = true;

    public synchronized void put(int value) throws InterruptedException {
        while (!empty) wait();
        content = value;
        empty = false;
        System.out.println("放入: " + value);
        notify();
    }

    public synchronized void get() throws InterruptedException {
        while (empty) wait();
        System.out.println("取出: " + content);
        empty = true;
        notify();
    }
}

public class ProducerConsumer {
    public static void main(String[] args) {
        Box box = new Box();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try { box.put(i); } catch (Exception e) {}
            }
        }, "生产者").start();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try { box.get(); } catch (Exception e) {}
            }
        }, "消费者").start();
    }
}

六、线程池(ThreadPoolExecutor)

相比频繁创建销毁线程,使用线程池更加高效。

6.1 使用 Executors 创建线程池

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑ExecutorService pool = Executors.newFixedThreadPool(3);

Runnable task = () -> System.out.println("执行:" + Thread.currentThread().getName());
for (int i = 0; i < 5; i++) pool.execute(task);

pool.shutdown();

6.2 自定义线程池参数

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑ExecutorService pool = new ThreadPoolExecutor(
    2, 5, 60, TimeUnit.SECONDS,
    new LinkedBlockingQueue<>(10),
    Executors.defaultThreadFactory(),
    new ThreadPoolExecutor.AbortPolicy()
);

七、定时任务执行(ScheduledExecutor)

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> {
    System.out.println("每隔2秒执行一次:" + System.currentTimeMillis());
}, 0, 2, TimeUnit.SECONDS);

🖼️ 图示:定时器执行周期结构图(初始延迟 → 周期性重复)


八、并发集合与工具类

类别

常用类名

并发集合

ConcurrentHashMap, CopyOnWriteArrayList

线程工具类

CountDownLatch, CyclicBarrier, Semaphore

原子类

AtomicInteger, AtomicBoolean


九、真实案例:并发下载模拟

代码语言:javascript
代码运行次数:0
运行
复制
java复制编辑public class DownloadSimulator {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);

        for (int i = 1; i <= 5; i++) {
            final int fileNum = i;
            pool.submit(() -> {
                System.out.println("开始下载文件" + fileNum);
                try { Thread.sleep(2000); } catch (Exception e) {}
                System.out.println("下载完成文件" + fileNum);
            });
        }

        pool.shutdown();
    }
}

十、总结与实践建议

内容

推荐工具 / 方法

创建线程

Runnable / Callable

同步控制

synchronized, Lock

并发数据结构

ConcurrentHashMap 等

执行管理

ThreadPoolExecutor

线程通信

wait/notify,BlockingQueue

定时任务

ScheduledExecutorService


十一、拓展阅读建议

  • 使用 ReentrantLock 精细控制线程锁行为
  • Java CompletableFuture 异步编程实践
  • 使用 ForkJoinPool 实现并行递归任务
  • Spring Boot 中使用线程池和异步方法

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、前言
  • 二、Java 创建线程的三种方式
    • 2.1 方式一:继承 Thread 类
    • 2.2 方式二:实现 Runnable 接口
    • 2.3 方式三:使用 Callable 和 Future
  • 三、线程的生命周期
  • 四、线程同步与互斥
    • 4.1 synchronized 关键字
    • 4.2 多线程卖票例子(避免超卖)
  • 五、线程通信机制(wait/notify)
    • 5.1 示例:生产者-消费者模型
  • 六、线程池(ThreadPoolExecutor)
    • 6.1 使用 Executors 创建线程池
    • 6.2 自定义线程池参数
  • 七、定时任务执行(ScheduledExecutor)
  • 八、并发集合与工具类
  • 九、真实案例:并发下载模拟
  • 十、总结与实践建议
  • 十一、拓展阅读建议
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档