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

如何在Java中进行多线程编程

在Java中进行多线程编程有多种方式,最常用的包括继承Thread类、实现Runnable接口、实现Callable接口,以及使用线程池等。以下是具体介绍和代码示例:

1. 继承Thread类

通过继承Thread类并重写run()方法来定义线程执行逻辑,然后调用start()方法启动线程。

// 继承Thread类
class MyThread extends Thread {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println("线程" + Thread.currentThread().getId() + ": " + i);try {Thread.sleep(100); // 休眠100毫秒,模拟任务耗时} catch (InterruptedException e) {e.printStackTrace();}}}
}public class ThreadExample {public static void main(String[] args) {// 创建并启动线程MyThread thread1 = new MyThread();MyThread thread2 = new MyThread();thread1.start(); // 启动线程(调用run()方法)thread2.start();}
}
 
 

2. 实现Runnable接口

实现Runnable接口的run()方法,将任务逻辑与线程分离,更灵活(可避免单继承限制)。

// 实现Runnable接口
class MyRunnable implements Runnable {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println("线程" + Thread.currentThread().getId() + ": " + i);try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}
}public class RunnableExample {public static void main(String[] args) {// 创建任务实例MyRunnable task = new MyRunnable();// 通过Thread包装任务并启动Thread thread1 = new Thread(task);Thread thread2 = new Thread(task);thread1.start();thread2.start();}
}
 
 

3. 实现Callable接口(带返回值)

Callable接口与Runnable类似,但call()方法可以返回结果并抛出异常,通常配合Future使用。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;// 实现Callable接口(泛型指定返回值类型)
class MyCallable implements Callable<Integer> {private int taskId;public MyCallable(int taskId) {this.taskId = taskId;}@Overridepublic Integer call() throws Exception {int sum = 0;for (int i = 0; i <= 10; i++) {sum += i;Thread.sleep(50);}System.out.println("任务" + taskId + "执行完毕,结果为:" + sum);return sum; // 返回计算结果}
}public class CallableExample {public static void main(String[] args) throws ExecutionException, InterruptedException {// 创建Callable任务MyCallable task1 = new MyCallable(1);MyCallable task2 = new MyCallable(2);// 用FutureTask包装Callable(可获取结果)FutureTask<Integer> future1 = new FutureTask<>(task1);FutureTask<Integer> future2 = new FutureTask<>(task2);// 启动线程new Thread(future1).start();new Thread(future2).start();// 获取任务结果(会阻塞直到任务完成)int result1 = future1.get();int result2 = future2.get();System.out.println("主线程获取结果:" + result1 + "," + result2);}
}
 
 

4. 使用线程池(推荐)

频繁创建销毁线程会消耗资源,线程池可以复用线程,提高效率。Java通过ExecutorsThreadPoolExecutor创建线程池。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class ThreadPoolExample {public static void main(String[] args) {// 创建固定大小的线程池(3个线程)ExecutorService executor = Executors.newFixedThreadPool(3);// 提交5个任务到线程池for (int i = 0; i < 5; i++) {final int taskId = i;executor.submit(() -> {// 使用Lambda表达式简化RunnableSystem.out.println("任务" + taskId + "由线程" + Thread.currentThread().getId() + "执行");try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}});}// 关闭线程池(不再接受新任务,等待现有任务完成)executor.shutdown();}
}
 
 

核心概念补充

  • 线程状态:新建(New)→ 就绪(Runnable)→ 运行(Running)→ 阻塞(Blocked/Waiting/Timed Waiting)→ 终止(Terminated)。
  • 线程同步:多线程共享资源时需避免竞争,可使用synchronized关键字、Lock接口等实现同步。
  • 线程通信:通过wait()notify()notifyAll()等方法实现线程间协作。

线程池是实际开发中推荐的方式,因为它能更好地管理线程资源,避免频繁创建线程的开销。

http://www.jsqmd.com/news/16739/

相关文章:

  • Java中java.util.Random的用法
  • 我的学习开始及历程
  • 2025年磨粉机厂家推荐排行榜,雷蒙磨粉机,环辊磨粉机,摆式磨粉机,矿石磨粉机,超微磨粉机,高压磨粉机公司推荐!
  • Java基础语法与面向对象
  • 从汇编角度看C++优化:编译器真正做了什么 - 教程
  • 实用指南:【从零开始学习RabbitMQ】
  • Godot-C#处理节点关系
  • 2025信息流代运营推荐:线尚网络精准投放,效果显著!
  • 零售行业绩效流程推行难点及 Tita 目标绩效一体化管理方案
  • CTFHub 信息泄露通关笔记4:备份文件下载 bak文件 - 教程
  • 软件工程-结队项目
  • go 并发赋值安全性
  • 《探索C语言中数组的奥秘(下)》 - 教程
  • Vue中keep-alive实现原理解析
  • 2025 年防撞钢护栏厂家推荐聊城市泰锌金属材料有限公司,桥梁,不锈钢,复合管,景观,灯光,热镀锌,河道,铝合金,绳索防撞钢护栏公司推荐
  • [转]学习指南 - PL-600:Microsoft Power Platform 解决方案架构师
  • 2025年聚氨酯制品厂家推荐排行榜,浇注型聚氨酯,聚氨酯预聚体,聚氨酯胶黏剂,聚氨酯组合料,液体聚氨酯,专业品质与创新技术之选
  • Java异步编程难题拆解
  • 三场比赛(二)
  • 深入学习Spring Boot框架
  • 2025年水产养殖设备厂家推荐排行榜,PP鱼池/微滤机/不锈钢微滤机/锦鲤池微滤机一体机/全自动污水过滤器/生物过滤器/循环水养殖系统公司推荐!
  • 预测不可预测之物的校准学习技术
  • java语言程序设计类与对象课后作业 - 20243867孙堃2405
  • 2025年智能防爆灯/工矿灯厂家推荐排行榜,专业安全与高效照明解决方案!
  • AI模型测评平台工程化实战十二讲(第五讲:大模型测评分享机制:安全、高效的结果展示与协作)
  • Java基础——包机制,JavaDoc生成文档
  • Java 无锁方式实现高性能线程
  • 用 【C# + Winform + MediaPipe】 构建人脸468点识别
  • 10.19日模考总结
  • 详细介绍:2020年美国新冠肺炎疫情数据分析与可视化